我正在将两个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());
当我运行上面的代码时,断点永远不会被触发。 有什么问题?
答案 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