Compare two dictionary (dic1, dic2)
1. Loop (Iterating through the key-value pairs)
if (dict1.Count != dict2.Count) return false;
foreach (var kvp in dict1)
{
if (!dict2.TryGetValue(kvp.Key, out var value) || !value.Equals(kvp.Value))
{
return false;
}
}
return true;
2. Compare two dictionaries in C# by invoking the SequenceEqual() method
{
if (dict1.Count != dict2.Count) return false;
return dict1.OrderBy(kvp => kvp.Key).SequenceEqual(dict2.OrderBy(kvp => kvp.Key));
}
3. use the Enumerable.All() method to check our dictionaries for equality:
if (dict1.Count != dict2.Count) return false;
return dict1.All(kvp => dict2.TryGetValue(kvp.Key, out var value) && value.Equals(kvp.Value));
- Loop is best.
- then Enumerable.All() method,
SequenceEqual()method, which runs is about 11x slower than theEnumerable.All()
Comments
Post a Comment