Why do you want to restrict K
and V
to being value types in the first place? I suggest you just remove the constraints. There are "interesting" things about dictionaries though - are two dictionaries which happen to have the same entries, but use different equality comparers equivalent? IDictionary<,>
doesn't have an equality comparer property, unfortunately, so you may need to provide on to your equivalence method. You'll need to consider what it even means to be equivalent here.
For example, two dictionaries both with case-insensitive equality comparers might have { "FOO", true } and { "foo", true } - to some extent they're equivalent, but to some extent they aren't. It depends on what you want to use the equivalence relation for.
EDIT: Here's an example which should be fine in most cases, but could give odd results if the two dictionaries treat keys differently:
public static bool EquivalentTo<TKey, TValue>(
this IDictionary<TKey, TValue> first,
IDictionary<TKey, TValue> second)
{
return first.EquivalentTo(second, EqualityComparer<TValue>.Default);
}
public static bool EquivalentTo<TKey, TValue>(
this IDictionary<TKey, TValue> first,
IDictionary<TKey, TValue> second,
IEqualityComparer<TValue> valueComparer)
{
if (first == second)
{
return true;
}
if (first == null || second == null)
{
return false;
}
if (first.Count != second.Count)
{
return false;
}
foreach (var firstKeyValue in first)
{
TValue secondValue;
if (!second.TryGetValue(firstKeyValue.Key, out secondValue) ||
!valueComparer.Equals(firstKeyValue.Value, secondValue))
{
return false;
}
}
return true;
}
Untested, but let me know if it does what you want...