I have several objects that depending on the use case are considered Equal differently.
I need to use these objects as keys for dictionaries and as far as I know Dictionary<>
use the Equals()
method which limits me to have only one implementation of it.
Is there any workaround to this? I expected to be able to inject a EqualityComparer
, a delegate or something so Dictionary<>
can use different ways of searching for items.
Thanks.
Any one dictionary can only have a single equality comparer. You can't ask it to find a key with respect to a particular equality comparer, because otherwise its stored hash codes will be useless, and it would have to just do a linear search.
If you have multiple equality comparers you want to search across, I'd keep several separate dictionaries, each with a different comparer.
(If you just wanted to be able to specify the equality comparer and had missed it, that's what the Dictionary(IEqualityComparer<TKey> comparer)
constructor is for).