我写了下面的代码来实现在可能的最基本的方式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 –