Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 27 / 68

Working with HashSet (Sets)

In this lesson you will learn how to hold duplicate-free data with HashSet in C#, and understand the basics of the set data structure. This is for anyone searching for "C# HashSet how to use".

HashSet<T> is a box that refuses to hold the same value twice. It is handy for stripping duplicates out of an array, or for checking membership quickly.

The sample code builds a set from the array {1, 2, 2, 3, 3, 3} with new HashSet<int>(nums); the duplicates disappear automatically and uniqueNums keeps only 1, 2, and 3. Notice how Contains() checks whether a value is present.

A common stumbling block for beginners is that the order of a HashSet is not guaranteed. Unlike an array, items are not necessarily kept in insertion order, so an array or List is a better fit when order matters.

In real-world development, HashSet's Contains() also outperforms a List's Contains() on larger data sets. SortedSet is a similar structure that does keep its contents ordered.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)