How to check whether two HashSets are equal in C# .NET

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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: