c# - linq & distinct,实现 equals 和 gethashcode

标签 c# .net linq

所以我正在尝试让它工作,但我似乎不知道为什么它不起作用

演示代码;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        var myVar = new List<parent >();
        myVar.Add(new parent() { id = "id1", blah1 = "blah1", c1 = new child() { blah2 = "blah2", blah3 = "blah3" } });
        myVar.Add(new parent() { id = "id1", blah1 = "blah1", c1 = new child() { blah2 = "blah2", blah3 = "blah3" } });

        var test = myVar.Distinct();

        Console.ReadKey();

    }
}


public class parent : IEquatable<parent>
{
    public String id { get;set;}
    public String blah1 { get; set; }
    public child c1 { get; set; }

    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            // Suitable nullity checks etc, of course :)
            hash = hash * 23 + id.GetHashCode();
            hash = hash * 23 + blah1.GetHashCode();
            hash = hash * 23 + (c1 == null ? 0 : c1.GetHashCode());
            return hash;
        }
    }

    public bool Equals(parent other)
    {
        return object.Equals(id, other.id) &&
            object.Equals(blah1, other.blah1) &&
            object.Equals(c1, other.c1);
    }

}

public class child : IEquatable<child>
{
    public String blah2 { get; set; }
    public String blah3 { get; set; }

    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            // Suitable nullity checks etc, of course :)
            hash = hash * 23 + blah2.GetHashCode();
            hash = hash * 23 + blah3.GetHashCode();
            return hash;
        }
    }

    public bool Equals(child other)
    {
        return object.Equals(blah2, other.blah2) &&
            object.Equals(blah3, other.blah3);
    }

}
}

有人能发现我的错误吗?

最佳答案

您需要覆盖 Equals(object)方法:

public override bool Equals(object obj) {
    return Equals(obj as parent);
}

object.Equals方法(不像 EqualityComparer<T>.Default )不使用 IEquatable界面。因此,当你写 object.Equals(c1, other.c1) ,它不会调用您的 Child.Equals(Child)方法。

对于 parent,您绝对不需要这样做同样,但您确实应该这样做。

关于c# - linq & distinct,实现 equals 和 gethashcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4786919/

相关文章:

c# - 错误 - 无法访问 IIS 元数据库

c# - 使用 System.Print 在 "Microsoft Print to PDF"打印机中设置文件名

c# - 发布到 Controller 时填充 subview 模型集合

c# - 找不到来自绑定(bind)到 ListBox 的导入命名空间的枚举

linq - 如何使用 Linq 和 IN 子句

c# - 如何使用 xUnit.net 进行单元测试控制台输出?

.net - 必须在 .net 中一次访问一个静态方法/类/变量吗?

c# - 使用 NetworkStream 传输文件

LINQ:将多个 int 属性连接成一个字符串

c# - 如何使用 linq 从 Excel 中检索数据?