首页 > 代码库 > linq 之 Distinct的使用
linq 之 Distinct的使用
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 }
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); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。