首页 > 其他 > 详细

linq 之 Distinct的使用

时间:2014-07-09 17:40:02      阅读:262      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1         public class Product
 2         {
 3             public string Name { get;set;}
 4             public int Code { get; set; }
 5         }
 6         class ProductComparet : IEqualityComparer<Product>
 7         {
 8             public bool Equals(Product x, Product y)
 9             {
10                 if (object.ReferenceEquals(x,y))
11                 {
12                     return true;
13                 }
14                 if (object.ReferenceEquals(x,null)||object.ReferenceEquals(y,null))
15                 {
16                     return false;
17                 }
18                 return x.Code == y.Code && x.Name == y.Name;
19             }
20 
21             public int GetHashCode(Product product)
22             {
23                 if (object.ReferenceEquals(product, null))
24                 {
25                     return 0;
26                 }
27                 int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
28 
29                 int hashProductCode = product.Code.GetHashCode();
30                 return hashProductName ^ hashProductCode;
31 
32             }
33         }
View Code

 

        static void Main(string[] args)
        {
   
            Product[] products = { new Product { Name = "apple", Code = 9 }, 
                       new Product { Name = "orange", Code = 4 }, 
                       new Product { Name = "apple", Code = 9 }, 
                       new Product { Name = "lemon", Code = 12 } };

            IEnumerable<Product> noduplicates = products.Distinct(new ProductComparet());
            foreach (var item in noduplicates)
            {
                Console.WriteLine(item.Name+" "+item.Code);
            }
        }

 

linq 之 Distinct的使用,布布扣,bubuko.com

linq 之 Distinct的使用

原文:http://www.cnblogs.com/yangpeng-jingjing/p/3831897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!