LINQ中使用Distinct去除重複的物件
.net中自帶的比較器Compare是值型別比較,要想比較物件,即引用型別.我們需要重寫比較器.
新建RefComparer.cs類
建立一個委託,用於傳入需要比較的物件
public delegate bool EqualsComparer<T>(T x, T y);
然後重寫Equals和GetHashCode方法即可
具體程式碼如下
public delegate bool EqualsComparer<T>(T x, T y);
/// <summary>
/// 引用型別比較器
/// </summary>
/// <typeparam name="T"></typeparam>
public class RefComparer<T> : IEqualityComparer<T>
{
private EqualsComparer<T> comparer;
public RefComparer(EqualsComparer<T> equalsComparer)
{
this.comparer = equalsComparer;
}
public bool Equals(T x, T y)
{
if (this.comparer != null)
return this.comparer(x, y);
else
return false;
}
public int GetHashCode(T obj)
{
return obj.ToString().GetHashCode();
}
}