Brief introduction
When using list or collection in C #, we often need to use the distinct operation, but the distinct overloaded method provided by Microsoft by default does not meet our needs. At this time, we need to do some work on our own.
Overloading of the distinct method
The distinct method of LINQ has one of the following overloaded versions:
public static IEnumerable<TSource> Distinc<TSource>( this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
which
Type parameter
TSource
The type of the element in source;
Parameters
Source
Type: System.Collections.Generic.IEnumerable <
tsource >
The sequence from which to remove the repeating element
Comparer
Type: System.Collections.Generic.IEqualityComparer <
tsource >
The IEqualityComparer T that is used to compare values <
>
.
return value
Type: System.Collections.Generic.IEnumerable <
tsource >
A IEnumerable <
T >
that contains non-repeating elements in the source sequence.
Implement IEqualityComparer
The key now is how to implement the comparer parameter in the method, and we want to do a comparer that works for each type, so we need to use the delegate.
OK, not much to say, the code is as follows:
usingSystem.collections.generic;namespace misstangproject.helperclass{ Public classListcomparer<t>: iequalitycomparer<t> { Public Delegate BOOLEqualscomparer<f> (f x, f y); PublicEqualscomparer<t> Equalscomparer; Public Listcomparer(equalscomparer<t> _euqlscomparer) { This. equalscomparer = _euqlscomparer; } Public BOOL Equals(t x, t y) {if(NULL! = Equalscomparer) {returnEqualscomparer (x, y); }Else{return false; } } Public int GetHashCode(T obj) {returnObj. ToString (). GetHashCode (); } }}
Using the distinct method of LINQ
Suppose we have a Boilerworkermodel class that has a code attribute, using the following method:
List<BoilerWorkerModel> newList = _list1.Distinct(new ListComparer<BoilerWorkerModel>((p1, p2) => (p1.Code == p2.Code))).ToList();
In this way, we have implemented the comparer that can be applied to all types of source, and can use the LINQ distinct method at will!
Get here, you're done.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C # implements the Distinct--ienumerable<t> of a Linq sequence;. Distinct<t> ()--iequalitycomparer