c# - 在 C# 中实现 Linq Distinct

标签 c# distinct

我编写了以下代码,以尽可能最基本的方式实现 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/

相关文章:

mysql - 如何选择按日期列 desc 排序的不同记录 - Laravel

c# - 如何防止浏览器的后退按钮被点击?

c# - 在 .NET Core 测试项目中构建时禁用/阻止 XUnit 警告

c# - EF 预编译 View 和自定义查询

mysql : do case when with condition distinct

select - 为什么 select count distinct 在 yii 中不起作用?

c# - 从部署的 Web 应用程序调用时,Azure 函数应用程序不会触发

c# - ColorAnimation 为滑动时的 listviewItem 颜色设置动画 - WP8.1

c# - Linq 到 SQL : SELECT latest DISTINCT entries

mysql - SQL获取不同的名字和姓氏