C# 在c中实现Linq Distinct#

C# 在c中实现Linq Distinct#,c#,distinct,C#,Distinct,我编写了以下代码,以最基本的方式实现Linq.Distinct(IEqualityComparer),但是simpleCollection返回2项,如果返回1项 奇怪的是,我注意到等于上的断点从未被击中 这可能与我实现的GetHashCode()有关吗 公共类testobjx { 公共整数i{get;set;} } 公共类mytest { 公用干管() { var simpleCollection=new[]{new testobjx(){i=1},new testobjx(){i=1}}.Di

我编写了以下代码,以最基本的方式实现
Linq.Distinct(IEqualityComparer)
,但是
simpleCollection
返回2项,如果返回1项

奇怪的是,我注意到
等于
上的断点从未被击中

这可能与我实现的
GetHashCode()
有关吗

公共类testobjx
{
公共整数i{get;set;}
}
公共类mytest
{
公用干管()
{
var simpleCollection=new[]{new testobjx(){i=1},new testobjx(){i=1}}.Distinct(new DistinctCodeType());
var itemCount=simpleCollection.Count();//这应该返回1而不是2。
}
}
公共类DistinctCodeType:IEqualityComparer
{
公共布尔等于(testobjx x,testobjx y)
{
返回x.i==y.i;
}
public int GetHashCode(testobjx obj)
{
返回obj.GetHashCode();
}
}
试试:


对象的GetHashCode的默认实现基于对象的实例,因此具有相同值的两个testobjx实例具有不同的哈希代码。您需要修改GetHashCode方法来查询对象的属性。如果对象有多个属性,则需要确定需要哪些属性来唯一标识该对象并从中组成单个哈希代码。

如果x、y或obj为空,该怎么办?如果GetHashCode的结果不匹配,则甚至不会检查Equals。处理GetHashCode实现。仅供参考:@AnthonyPegram-如果我只是
返回0
,那么这是将所有事情都推迟到Equals方法的合法方式吗?@maxp,不。这将是完全不理想的处理方式。你不想把一切都推给平等的人,那太贵了。实现必须检查集合中的所有内容,而无需这样做。如果你不熟悉,你应该仔细阅读哈希表是如何工作的,因为在幕后,这就是Distinct中使用的。如果类不只是包含一个整数,而是包含10个独立的整数或任何其他数量的复杂属性,那么该方法会是什么呢?@maxp,看看这个答案。此外,VS插件(如ReSharper)能够生成一些常见接口和方法的实现,包括GetHashCode。GetHashCode的默认实现并不唯一标识对象。不可能。它有40亿个可能的值,最确定的是有40多亿个可能的对象。但即便如此,你也会开始变得更聪明。注意将唯一性与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();
}