码迷,mamicode.com
首页 > 其他好文 > 详细

linq 之 Distinct的使用

时间:2014-07-09 17:39:41      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   os   

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的使用

标签:style   blog   http   color   使用   os   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!