IEqualityComparer使用两个属性失败

时间:2018-04-06 15:13:03

标签: c# distinct equality iequalitycomparer

当我在Distinct()中使用这个比较器时,它总是返回false。无法理解原因。

public class IdEqualityComparer : IEqualityComparer<Relationship>
{
    public bool Equals(Relationship x, Relationship y)
    {
        if (x == null && y == null)
            return true;
        else if (x == null || y == null)
            return false;
        else if (x.ID == y.ID && x.RelatedID == y.RelatedID)
            return true;
        else
            return false;
    }

    public int GetHashCode(Relationship obj)
    {
        unchecked
        {
            int hash = (obj.ID ?? "").GetHashCode() ^ (obj.RelatedID ?? "").GetHashCode();
            return hash;
        }
    }
}

哈希似乎对我来说是正确的,但ID和RelatedID比较永远不会返回true。

它失败了,因为我可以在之后检查结果,并且使用这两个属性输出不明显。

2 个答案:

答案 0 :(得分:1)

向所有人道歉!它工作正常。

我正在比较与Marc的答案类似定义的对象。但是,我这样做了:

var relators = relationships.Distinct(new RelationshipEqualityComparer());

然后将关系(而不是房地产经纪人)发送到审核项目的下一个方法。有时需要另外一双眼睛!

谢谢!

答案 1 :(得分:0)

似乎在这里工作正常;

static void Main()
{
    var objs = new[]
    {
        new Relationship { ID = "a", RelatedID = "b" }, // <----\
        new Relationship { ID = "a", RelatedID = "c" }, //      |
        new Relationship { ID = "a", RelatedID = "b" }, // dup--/
        new Relationship { ID = "d", RelatedID = "b" }, // <------\
        new Relationship { ID = "d", RelatedID = "c" }, //        |
        new Relationship { ID = "d", RelatedID = "b" }, // dup ---/ 
        new Relationship { ID = "b", RelatedID = "c" }, //
    };

    var count = objs.Distinct(new IdEqualityComparer()).Count();
    System.Console.WriteLine(count);
}

提供5,而非7(如果它始终返回false,我们会期望这样做)。经测试:

public class Relationship
{
    public string ID { get; set; }
    public string RelatedID { get; set; }
}

为了更清楚地说明这一点:

var a = new Relationship { Id = "x", RelatedID = "foo" };
var b = new Relationship { Id = "y", RelatedID = "foo" };
var c = new Relationship { Id = "x", RelatedID = "foo" };

我们现在可以证明比较器适当地返回truefalse

var comparer = new IdEqualityComparer();
Console.WriteLine(comparer.Equals(a, b)); // False
Console.WriteLine(comparer.Equals(a, c)); // True

我们还可以证明哈希码正常工作:

Console.WriteLine(comparer.GetHashCode(a));
Console.WriteLine(comparer.GetHashCode(b));
Console.WriteLine(comparer.GetHashCode(c));

请注意,这些数字会改变,但对我来说这会给出:

-789327704
1132350395
-789327704

数字并不重要 - 重要的是第一个和最后一个是相同的,并且(理想情况下)与中间数字不同。

所以:比较器工作正常,问题的前提是不正确的。您需要在代码中识别 有什么不同,并修复它。