Created
March 6, 2024 12:48
-
-
Save jskeet/809fa5dad31aaa45a53d7c58ab119a4c to your computer and use it in GitHub Desktop.
Full example from https://stackoverflow.com/questions/78112372
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main() | |
{ | |
Dictionary<string, object> dict1 = new Dictionary<string, object>() | |
{ | |
{"Key1","1"}, | |
{"Key2",2}, | |
{"Key3","4"}, | |
{"Key4",3}, | |
}; | |
Dictionary<string, object> dict2 = new Dictionary<string, object>() | |
{ | |
{"Key1","1"}, | |
{"Key2",2}, | |
{"Key3","3"}, | |
{"Key4",4}, | |
}; | |
List<KeyValuePair<string, object>> differences = GetDifferences(dict1, dict2).ToList(); | |
// Output (not necessarily in this order): | |
// Key3: 4 | |
// Key4: 3 | |
foreach (var pair in differences) | |
{ | |
Console.WriteLine($"{pair.Key}: {pair.Value}"); | |
} | |
} | |
public static IEnumerable<KeyValuePair<string, object>> GetDifferences( | |
Dictionary<string, object> x, Dictionary<string, object> y) | |
{ | |
return x.Except(y, new KeyValuePairComparer<string, object>()); | |
} | |
} | |
public class KeyValuePairComparer<TKey, TValue> | |
: IEqualityComparer<KeyValuePair<TKey, TValue>> | |
{ | |
public bool Equals(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y) | |
{ | |
return EqualityComparer<TKey>.Default.Equals(x.Key, y.Key) && | |
EqualityComparer<TValue>.Default.Equals(x.Value, y.Value); | |
} | |
public int GetHashCode(KeyValuePair<TKey, TValue> obj) | |
{ | |
return EqualityComparer<TKey>.Default.GetHashCode(obj.Key) ^ | |
EqualityComparer<TValue>.Default.GetHashCode(obj.Value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment