我寫了下面的代碼來實現在可能的最基本的方式Linq.Distinct(IEqualityComparer)
顯着,但是simpleCollection
回報2項,而是如果1實施中的LINQ C#
奇怪的是,我已經注意到,在Equals
斷點永遠不會命中。
難道這與我執行GetHashCode()
有關嗎?
public class testobjx
{
public int i { get; set; }
}
public class mytest
{
public Main()
{
var simpleCollection = new[] { new testobjx() { i = 1 }, new testobjx() { i = 1 } }.Distinct(new DistinctCodeType());
var itemCount = simpleCollection.Count();//this should return 1 not 2.
}
}
public class DistinctCodeType : IEqualityComparer<testobjx>
{
public bool Equals(testobjx x, testobjx y)
{
return x.i == y.i;
}
public int GetHashCode(testobjx obj)
{
return obj.GetHashCode();
}
}
如果x,y或obj爲空,該怎麼辦? – n8wrl
如果GetHashCode的結果不匹配,則甚至不檢查Equals。處理你的GetHashCode實現。 –
供參考:http://msmvps.com/blogs/jon_skeet/archive/2010/12/30/reimplementing-linq-to-objects-part-14-distinct.aspx –