Usually, we use Distinct in C# for array deduplication, general array-based data types, such as int, string. can also be used for object deduplication, let's take a look at C#'s definition of Distinct method:
There is a heavy load, the first parameter is added this, which is the expansion method, about the expansion method, please Baidu understand. Let's study Distinct's object deduplication, let's say we now have a People class:
We declare a collection of ListPeole objects:
Let's use the Distinct method on ListPeople without any parameters, and the result is as follows:
It can be seen that if the Distinct method does not have parameters, it will deduplicate p, p1, p2 in the object set, and there is no deduplication for different objects with the same member value of the object. Now we have a requirement, for People with the same ID, we count as the same person, to output the non-duplicate people in the set (just output one for the same ID), at this time, we use the second method of Distinct, the method requires that the parameters passed in are of type IEqualityComparer, inheriting a generic interface, we add the following code:
Inheriting the IEqualityComparer interface, you must implement the Equals and GetHashCode methods. When we compare, we can pass in an entity with a PeopleCompareByID:
The results of the run are as follows:
We have achieved the effect of deduplication by ID. Now the requirements have changed again, the ID and the province are the same person, to output the person's information (the same can output one at will), at this time, we see that ID=0 and Province="Hubei" are duplicated, to deduplicate it, we have another class, or inherit from IEqualityComparer:
Similarly, when using the Distinct method, an instance of PeopleCompareByIDAndProvince is passed:
The results after running are as follows:
Achieved the effect we wanted. This method can be used when encountering the problem of deduplication with three or more object members to determine whether the object is duplicated. The above is my humble opinion.
|