Skip to content

Instantly share code, notes, and snippets.

@rossmurray
Created April 25, 2014 22:59
Show Gist options
  • Save rossmurray/11305998 to your computer and use it in GitHub Desktop.
Save rossmurray/11305998 to your computer and use it in GitHub Desktop.
Dictionary comparer, great for grouping dictionaries with LINQ. GetHashCode implementation could use work.
public class KeyEqualityComparer<T, U> : IEqualityComparer<KeyValuePair<T, U>>
{
public bool Equals(KeyValuePair<T, U> x, KeyValuePair<T, U> y)
{
return (x.Key.Equals(y.Key) && x.Value.Equals(y.Value));
}
public int GetHashCode(KeyValuePair<T, U> obj)
{
return obj.Key.GetHashCode();
}
}
public class DictionaryComparer<T, U> : IEqualityComparer<IDictionary<T, U>>
{
public bool Equals(IDictionary<T, U> a, IDictionary<T, U> b)
{
var result = a.SequenceEqual(b, new KeyEqualityComparer<T, U>());
return result;
}
public int GetHashCode(IDictionary<T, U> d)
{
return d.Aggregate("", (a,b) => b.Key.ToString()).GetHashCode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment