在IEqualityComparer

时间:2018-05-10 07:09:26

标签: c# linq iequalitycomparer

我正在将两个List<Dictionary<string, object>>与我自己的IEqualityComparer<Dictionary<string, object>>实现进行比较,但GetHashCode和Equals方法都不会被调用。

这是我自己的IEqualityComparer实现。

public class TestEqualityComparer : IEqualityComparer<Dictionary<string, object>>
{
    public bool Equals(Dictionary<string, object> a, Dictionary<string, object> b)
    {
        return true; // breakpoint here
    }

    public int GetHashCode(Dictionary<string, object> obj)
    {
        return 0; // breakpoint here
    }
}

这是一个实际的比较代码。

var a = new List<Dictionary<string, object>>();
var b = new List<Dictionary<string, object>>();

a.Add(new Dictionary<string, object> { ["id"] = 1, ["msg"] = "aaaaa" });
a.Add(new Dictionary<string, object> { ["id"] = 2, ["msg"] = "bbbbb" });
a.Add(new Dictionary<string, object> { ["id"] = 3, ["msg"] = "ccccc" });

b.Add(new Dictionary<string, object> { ["id"] = 1, ["msg"] = "zzzzz" });
b.Add(new Dictionary<string, object> { ["id"] = 2, ["msg"] = "bbbbb" });
b.Add(new Dictionary<string, object> { ["id"] = 4, ["msg"] = "ddddd" });

var except = a.Except(b, new TestEqualityComparer());

当我运行上面的代码时,断点永远不会被触发。 有什么问题?

1 个答案:

答案 0 :(得分:5)

LINQ uses deferred execution Here以来,除非您决定对其进行迭代,否则将无法确定except集合的内容,因此无法调用IEqualityComparer

要强制评估您的Except语句,您可以使用foreach对其进行迭代,或将ToList/ToArray附加到您的语句中,如下所示:

var except = a.Except(b, new TestEqualityComparer()).ToList(); // ToList forces processing of LINQ query