When we think of deduplication on an enumerable object collection, the first thing we think of is Linq's Distinct method.
Define a class first, and then use the Distinct method to dereduce it
class Man { public int Age { get; set; } public string Name { get; set; } public string Adress { get; set; } public decimal Weight { get; set; } public decimal Height { get; set; } }
List<Man> list = new List<Man>() { new Man(){Age=21,Name="Adam",Adress="Shenzhen",Weight=60,Height=170}, new Man(){Age=21,Name="Adam",Adress="Shenzhen",Weight=60,Height=170} }; var distinct = ();
However, the Count of the distinct set obtained by deduplication is still two, and there are still two Adams in the set.
In fact, the comparison of the declared references in the Distinct method is the same as the False obtained by using the Equals() method for objects with exactly the same attributes.
Therefore, we need to use overload when using Distinct method for object collectionsDistinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);
To use this method, we have to override the IEqualityComparer interface and then use the Distinct method:
public class ManComparer : IEqualityComparer<Man> { public bool Equals(Man x, Man y) { return == && == && == && == && == ; } public int GetHashCode(Man obj) { return (); } } var distinct = (new ManComparer());
However, again, there are still two objects in the distinct collection.
In fact, since the HashCode of the object is directly retrieved, the comparison speed with HashCode is faster than the Equals method.
Therefore, IEqualityComparer will use the GetHashCode method before using Equals, and immediately determine that the objects are equal when the HashCodes of both objects are the same.
When the two objects HashCodes are different, the Equals method will be called to judge the object to be compared.
Since the two references in the list in the above example are actually two different objects, the HashCode must be different
So to trigger the Equlas method, we need to change GetHashCode and let it return the same constant
public class ManComparerNew : IEqualityComparer<Man> { public bool Equals(Man x, Man y) { return == && == && == && == && == ; } public int GetHashCode(Man obj) { return 1; } } var distinct = (new ManComparerNew());
Now there is only one Man object in the distinct collection, and the deduplication is successfully implemented.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.