Enumerable.Distinct Method in C#

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(System.Linq.Enumerable.Distinct%60%601);k(SolutionItemsProject);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.6.1);k(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.8

public class Product { public string Name { get; set; } public int Code { get; set; } } // Custom comparer for the Product class class ProductComparer : IEqualityComparer<Product> { // Products are equal if their names and product numbers are equal. public bool Equals(Product x, Product y) { //Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) return true; //Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; //Check whether the products' properties are equal. return x.Code == y.Code && x.Name == y.Name; } // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. public int GetHashCode(Product product) { //Check whether the object is null if (Object.ReferenceEquals(product, null)) return 0; //Get hash code for the Name field if it is not null. int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode(); //Get hash code for the Code field. int hashProductCode = product.Code.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; } }
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 } }; //Exclude duplicates. IEnumerable<Product> noduplicates = products.Distinct(new ProductComparer()); foreach (var product in noduplicates) Console.WriteLine(product.Name + " " + product.Code); /* This code produces the following output: apple 9 orange 4 lemon 12 */

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE