How to check whether two HashSets are equal in C# .NET
September 1, 2017 Leave a comment
Two HashSet objects in C# are equal if they contain the same values regardless of their order in the collection.
Consider the following integer sets:
HashSet<int> intHashSetOne = new HashSet<int>() { 1,2,6,5,7,5 }; HashSet<int> intHashSetTwo = new HashSet<int>() { 2,2,8,5,9,4 }; HashSet<int> intHashSetThree = new HashSet<int>() { 6,7,5,5,2,1 };
You’ll see that intHashSetTwo contains different elements than intHashSetOne. intHashSetThree on the other hand has the same elements although in a different order. The HashSet.SetEquals method accepts any argument of type IEnumerable of T, such as lists or arrays, and will return true if the supplied collection has the same elements:
Debug.WriteLine(intHashSetTwo.SetEquals(intHashSetOne)); Debug.WriteLine(intHashSetThree.SetEquals(intHashSetOne));
This will print…
False
True
…as expected.
Like we saw in the post on HashSets referenced above this won’t automatically work for reference types as .NET cannot possibly guess how two custom objects can be compared and equated. You’ll need to supply a comparer which implements IEqualityComparer of T:
HashSet<Band> bandsOne = new HashSet<Band>(new BandNameComparer()); bandsOne.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 }); bandsOne.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 }); bandsOne.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 }); HashSet<Band> bandsTwo = new HashSet<Band>(new BandNameComparer()); bandsTwo.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 }); bandsTwo.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 }); bandsTwo.Add(new Band() { YearFormed = 1979, Name = "Well known band", NumberOfMembers = 4, NumberOfRecords = 10 }); HashSet<Band> bandsThree = new HashSet<Band>(new BandNameComparer()); bandsThree.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 }); bandsThree.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 }); bandsThree.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 }); Debug.WriteLine(bandsThree.SetEquals(bandsOne)); Debug.WriteLine(bandsTwo.SetEquals(bandsOne));
For details take a look at the post referenced above.
This will print…
True
False
…as our Band comparison is based on band names only:
public class BandNameComparer : IEqualityComparer<Band> { public bool Equals(Band x, Band y) { return x.Name.Equals(y.Name, StringComparison.InvariantCultureIgnoreCase); } public int GetHashCode(Band obj) { return obj.Name.GetHashCode(); } }
View all various C# language feature related posts here.