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); } }
linq 之 Distinct的使用
时间: 2024-10-07 14:49:17