(I assume that you want to group both sets as equals - the question is not very clear)
As is often the case with LINQ, scaffolding already exists for this, and what needs to be done is to provide a custom IEqualityComparer<T> appropriate method. In this case, this means this overload .
There is a generic IEqualityComparer<ISet<T>> that declares two sets equal if their intersection is the same as both of them:
class SetComparer<T> : IEqualityComparer<ISet<T>> { public bool Equals(ISet<T> lhs, ISet<T> rhs) { // null checks omitted return lhs.SetEquals(rhs); } public int GetHashCode(ISet<T> set) { // Not the best choice for a hash function in general, // but in this case it just fine. return set.Count; } }
And this is how you would group both sets under the same umbrella:
new List<HashSet<int>> { new HashSet<int> { 4 }, new HashSet<int> { 4 } }.GroupBy (x => x, new SetComparer<int>()).Count();
Jon
source share