I'm comparing two List<Dictionary<string, object>>
with my own IEqualityComparer<Dictionary<string, object>>
implementation, but neither GetHashCode nor Equals method get called.
Here's my own IEqualityComparer implementation.
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
.
To force evaluation of your Except
statement you can either iterate over it with foreach
or append ToList/ToArray
to your statement, like so:
var except = a.Except(b, new TestEqualityComparer()).ToList(); // ToList forces processing of LINQ query