9

我有以下课程:

public class SupplierCategory : IEquatable<SupplierCategory>
{
    public string Name { get; set; }
    public string Parent { get; set; }

    #region IEquatable<SupplierCategory> Members

    public bool Equals(SupplierCategory other)
    {
        return this.Name == other.Name && this.Parent == other.Parent;
    }

    #endregion
}

public class CategoryPathComparer : IEqualityComparer<List<SupplierCategory>>
{
    #region IEqualityComparer<List<SupplierCategory>> Members

    public bool Equals(List<SupplierCategory> x, List<SupplierCategory> y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(List<SupplierCategory> obj)
    {
        return obj.GetHashCode();
    }

    #endregion
}

我正在使用以下 linq 查询:

CategoryPathComparer comparer = new CategoryPathComparer();
List<List<SupplierCategory>> categoryPaths = (from i in infoList
                                                          select
                                                            new List<SupplierCategory>() { 
                                                             new SupplierCategory() { Name = i[3] },
                                                             new SupplierCategory() { Name = i[4], Parent = i[3] },
                                                             new SupplierCategory() { Name = i[5], Parent = i[4] }}).Distinct(comparer).ToList();

但是 distinct 并没有做我想做的事情,如以下代码所示:

comp.Equals(categoryPaths[0], categoryPaths[1]); //returns True

我是否以错误的方式使用它?为什么他们没有按照我的意图进行比较?

编辑:为了证明比较器确实有效,以下返回 true,因为它应该:

List<SupplierCategory> list1 = new List<SupplierCategory>() {
    new SupplierCategory() { Name = "Cat1" },
    new SupplierCategory() { Name = "Cat2", Parent = "Cat1" },
    new SupplierCategory() { Name = "Cat3", Parent = "Cat2" }
};
List<SupplierCategory> list1 = new List<SupplierCategory>() {
    new SupplierCategory() { Name = "Cat1" },
    new SupplierCategory() { Name = "Cat2", Parent = "Cat1" },
    new SupplierCategory() { Name = "Cat3", Parent = "Cat2" }
};
CategoryPathComparer comp = new CategoryPathComparer();
Console.WriteLine(comp.Equals(list1, list2).ToString());
4

2 回答 2

11

您的问题是您没有IEqualityComparer正确实施。

实现时IEqualityComparer<T>必须实现GetHashCode任何两个相等的对象具有相同的哈希码。

否则,您将得到不正确的行为,正如您在此处看到的那样。

您应该按如下方式实现 GetHashCode:(由this answer提供)

public int GetHashCode(List<SupplierCategory> obj) {
    int hash = 17;

    foreach(var value in obj)
        hash = hash * 23 + obj.GetHashCode();

    return hash;
}

您还需要覆盖GetHashCodeinSupplierCategory以保持一致。例如:

public override int GetHashCode() {
    int hash = 17;
    hash = hash * 23 + Name.GetHashCode();
    hash = hash * 23 + Parent.GetHashCode();
    return hash;
}

最后,尽管您不需要这样做,但您可能应该重写EqualsinSupplierCategory并使其调用Equals您为IEquatable.

于 2009-10-25T13:53:29.400 回答
4

实际上,这个问题甚至包含在文档中:http: //msdn.microsoft.com/en-us/library/bb338049.aspx

于 2009-11-03T00:51:39.893 回答