[英]Neither Equals nor GetHashCode get called on IEqualityComparer
I'm comparing two List<Dictionary<string, object>>
with my own IEqualityComparer<Dictionary<string, object>>
implementation, but neither GetHashCode nor Equals method get called. 我正在将两个
List<Dictionary<string, object>>
与我自己的IEqualityComparer<Dictionary<string, object>>
实现进行比较,但是不会调用GetHashCode和Equals方法。
Here's my own IEqualityComparer implementation. 这是我自己的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
}
}
And here's a actual comparing code. 这是一个实际的比较代码。
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());
When I ran the above code, breakpoints never got triggered. 当我运行上面的代码时,断点永远不会被触发。 What's the problem?
有什么问题?
Since LINQ uses deferred execution the contents of except
collection will not be determined unless you decide to iterate over it, hence no calls to your IEqualityComparer
. 由于LINQ使用延迟执行 ,因此除非您决定对其进行迭代,否则将不会确定
except
集合的内容,因此不会调用IEqualityComparer
。
To force evaluation of your Except
statement you can either iterate over it with foreach
or append ToList/ToArray
to your statement, like so: 要强制评估您的
Except
语句,您可以使用foreach
迭代它或将ToList/ToArray
附加到您的语句,如下所示:
var except = a.Except(b, new TestEqualityComparer()).ToList(); // ToList forces processing of LINQ query
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.