Is this the best way to create a comparer for the equality of two dictionaries? This needs to be exact. Note that Entity.Columns is a dictionary of KeyValuePair(string, object) :
public class EntityColumnCompare : IEqualityComparer<Entity>
{
public bool Equals(Entity a, Entity b)
{
var aCol = a.Columns.OrderBy(KeyValuePair => KeyValuePair.Key);
var bCol = b.Columns.OrderBy(KeyValuePAir => KeyValuePAir.Key);
if (aCol.SequenceEqual(bCol))
return true;
else
return false;
}
public int GetHashCode(Entity obj)
{
return obj.Columns.GetHashCode();
}
}
Also not too sure about the GetHashCode implementation.
Thanks!
It seems good to me, perhaps not the fastest but working.
You just need to change the
GetHashCode
implementation that is wrong.For example you could return
obj.Columns.Count.GetHashCode()
Here's what I would do:
That way you don't need to order the entries (which is a O(n log n) operation) : you only need to enumerate the entries in the first dictionary (O(n)) and try to retrieve values by key in the second dictionary (O(1)), so the overall complexity is O(n).
Also, note that your
GetHashCode
method is incorrect: in most cases it will return different values for different dictionary instances, even if they have the same content. And if the hashcode is different,Equals
will never be called... You have several options to implement it correctly, none of them ideal:GetHashCode
needs to be fastEquals
will always be called: very bad if you want to use this comparer in a hashtable/dictionary/hashset, because all instances will fall in the same bucket, resulting in O(n) access instead of O(1)Count
of the dictionary (as suggested by digEmAll): it won't give a great distribution, but still better than always returning the same value, and it satisfies the constraint forGetHashCode
(i.e. objects that are considered equal should have the same hashcode; two "equal" dictionaries have the same number of items, so it works)Something like this comes to mind, but there might be something more efficient: