简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM