I want to have a custom equality comparer IEnumerable
s. using @PaulZahra's code, I created the following class:
class CustomEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
var enumerables = new Dictionary<T, uint>();
foreach (T item in x)
{
enumerables.Add(item, 1);
}
foreach (T item in y)
{
if (enumerables.ContainsKey(item))
{
enumerables[item]--;
}
else
{
return false;
}
}
return enumerables.Values.All(v => v == 0);
}
public int GetHashCode(IEnumerable<T> obj) => obj.GetHashCode();
}
The problem is that if T
itself is an IEnumerable
, then ContainsKey
will check for reference equality, while the point of this equality comparer is to check for value equality at any given depth.
I thought to use .Keys.Contains()
instead, since it can accept an IEqualityComparer
as an argument:
if (enumerables.Keys.Contains(item, this)) // not sure if "this" or a new object
but I get the following error (CS1929):
'Dictionary.KeyCollection' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains(IQueryable, T, IEqualityComparer)' requires a receiver of type 'IQueryable'
I am not sure how to approach this. How to fix it? Thanks.
Edit: Note that this comparer doesn't care about order.