我编写了以下代码,以尽可能最基本的方式实现 Linq.Distinct(IEqualityComparer)
,但是 simpleCollection
返回 2 个项目,而不是 1 个项目。
奇怪的是,我注意到 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();
}
}
最佳答案
尝试:
public int GetHashCode(testobjx obj)
{
if (obj == null) return 0;
return obj.i.GetHashCode();
}
关于c# - 在 C# 中实现 Linq Distinct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12919571/