I want to compare the contents of two Dictionary
instances regardless of the order of the items they contain. SequenceEquals
var contentsEqual = source.DictionaryEqual(target);
// ...
public static bool DictionaryEqual(
this IDictionary first, IDictionary second)
{
return first.DictionaryEqual(second, null);
}
public static bool DictionaryEqual(
this IDictionary first, IDictionary second,
IEqualityComparer valueComparer)
{
if (first == second) return true;
if ((first == null) || (second == null)) return false;
if (first.Count != second.Count) return false;
valueComparer = valueComparer ?? EqualityComparer.Default;
foreach (var kvp in first)
{
TValue secondValue;
if (!second.TryGetValue(kvp.Key, out secondValue)) return false;
if (!valueComparer.Equals(kvp.Value, secondValue)) return false;
}
return true;
}