Skip to content

Instantly share code, notes, and snippets.

@jskeet
Created March 6, 2024 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jskeet/809fa5dad31aaa45a53d7c58ab119a4c to your computer and use it in GitHub Desktop.
Save jskeet/809fa5dad31aaa45a53d7c58ab119a4c to your computer and use it in GitHub Desktop.
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