簡介
在C#中使用List或者Collection的時候,我們經常需要使用到Distinct操作,但是微軟默認提供的Distinct重載方法並不能滿足我們的需求。這時候,我們就需要自己動手做一番工作了。
Distinct方法的重載
Linq的Distinct的方法有如下一個重載版本:
public static IEnumerable<TSource> Distinc<TSource>(
this IEnumerable<TSource> source,
IEqualityComparer<TSource> comparer
)
其中:
類型參數
TSource
source中的元素類型;
參數
source
類型: System.Collections.Generic.IEnumerable<
TSource>
要從中移除重複元素的序列
comparer
類型:System.Collections.Generic.IEqualityComparer<
TSource>
用於比較值的 IEqualityComparer<
T>
。
返回值
類型:System.Collections.Generic.IEnumerable<
TSource>
一個 IEnumerable<
T>
,包含源序列中的非重複元素。
實現IEqualityComparer
現在關鍵就是如何實現方法中的comparer 參數,我們希望做一個能夠適用於各個類型的comparer,這樣,我們就需要用到委託。
好,話不多說,代碼如下:
using System.Collections.Generic;
namespace MissTangProject.HelperClass
{
public class ListComparer<T> : IEqualityComparer<T>
{
public delegate bool EqualsComparer<F>(F x, F y);
public EqualsComparer<T> equalsComparer;
public ListComparer(EqualsComparer<T> _euqlsComparer)
{
this.equalsComparer = _euqlsComparer;
}
public bool Equals(T x, T y)
{
if (null != equalsComparer)
{
return equalsComparer(x, y);
}
else
{
return false;
}
}
public int GetHashCode(T obj)
{
return obj.ToString().GetHashCode();
}
}
}
使用Linq的Distinct方法
假設我們有一個BoilerWorkerModel類,該類有一個code屬性,使用方法如下:
List<BoilerWorkerModel> newList = _list1.Distinct(new ListComparer<BoilerWorkerModel>((p1, p2) => (p1.Code == p2.Code))).ToList();
這樣,我們就實現了能夠適用於各個類型source的comparer了,可以隨意的使用Linq的Distinct方法了!
到這裏,大功告成。