How do you determine if two HashSets are equal (by value, not by reference)?
Asked Answered
L

2

89

I am trying to determine if two HashSet objects in .NET 3.5 (C#) are equal sets, i.e. contain the same values. This seems like something one would obviously want to do but none of the provided functions seem to give you this information.

The way I can think to do this is by checking if the count of the two sets are equal and one set is a subset (not proper) of the other. I think the only way that can happen is if they are equal sets. Example code:

HashSet<int> set1 = new HashSet<int>();
set1.Add(1);
set1.Add(2);
set1.Add(3);

HashSet<int> set2 = new HashSet<int>();
set2.Add(1);
set2.Add(2);
set2.Add(3);

if(set1.Count == set2.Count && set1.IsSubsetOf(set2))
{
    // do something
}

Would this always work? Is there a better way? Why doesn't HashSet have a public bool IsEqualSetWith() function?

Laminitis answered 30/1, 2009 at 1:49 Comment(4)
It's called IEqualityComparer :)Tarryn
There is nothing wrong with SetEquals.Duplessismornay
Note that the order of addition has nothing to do with hashset equality.Defence
For anyone wanting an interface for accessing SetEquals, there is ISet<T> in System.Collections.GenericVenge
W
165

Look at the method SetEquals.

my_hashset.SetEquals(other);
Wein answered 30/1, 2009 at 1:56 Comment(4)
Thanks Michael, I don't know how I completely missed that in the method list on MSDN...Laminitis
Happens to everyone at one time or another. I just can't believe I beat out both Jon Skeet and Marc Gravell on a .NET question. I guess they do have to sleep sometime.Wein
Easy to miss. With the prefix "Set", the method looks like it is a mutator if you're not paying close attentionKrak
@MerlynMorgan-Graham: I never thought that way in a set theory context but an interesting catch anyway.Disharmony
T
5
IEqualityComparer<HashSet<int>> comp = HashSet<int>.CreateSetComparer();
Console.WriteLine("CreateSetComparer set1 == set2 : {0}", comp.Equals(set1, set2));
// or
bool areEqual = HashSet<int>.CreateSetComparer().Equals(set1, set2);
Torbart answered 24/4, 2014 at 7:15 Comment(1)
This is useful when you for example need to create a Dictionary where HashSet is used as a key.Delamare

© 2022 - 2024 — McMap. All rights reserved.