In C#, HashSet<T> is a collection of unique items. Think of a guest list at the door: a name is either on the list or it is not, and writing the same name twice does not put it there twice. You put items in with Add(), ask about them with Contains(), and take them out with Remove().
A HashSet finds an item in about O(1) time on average, which is much faster than scanning a list. It has no indexer (you cannot write set[0]) and no fixed order. It lives in the System.Collections.Generic namespace, so add using System.Collections.Generic; at the top of your file.
When you loop over a HashSet, items may come out in any order, and that order can change after you add or remove items. If you need a fixed order, copy the items to a List and sort it, or use SortedSet<T>.
Syntax
C# Syntax
Common first steps:
C#
using System.Collections.Generic;
HashSet<string> names = new HashSet<string>();
bool first = names.Add("Asha"); // true: new item
bool again = names.Add("Asha"); // false: already there
bool has = names.Contains("Asha"); // true
int total = names.Count; // 1
// Ignore upper and lower case when comparing items:
HashSet<string> loose = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Reference
HashSet vs List, Dictionary, and SortedSet
Pick the collection that matches what you need to do most:
Type
Stores
Order and repeats
Good for
HashSet<T>
Unique items
No repeats, no promised order
Fast "is it in there?" checks, removing duplicates, set math
List<T>
Items by position
Keeps order, allows repeats
An ordered list that grows and shrinks
Dictionary<TKey,TValue>
Key and value pairs
Unique keys, no promised order
Finding a value from a key
SortedSet<T>
Unique items
No repeats, always sorted
Unique items you must read in sorted order (slower, about O(log n))
Reference
Set Operations at a Glance
Say A = {1, 2, 3} and B = {3, 4, 5}. The first four methods change A in place. The rest only return true or false.
A first program: add three numbers, try to add one of them again, and check what is inside.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> numbers = new HashSet<int>();
Console.WriteLine(numbers.Add(10));
Console.WriteLine(numbers.Add(20));
Console.WriteLine(numbers.Add(10));
Console.WriteLine(numbers.Count);
Console.WriteLine(numbers.Contains(20));
Console.WriteLine(numbers.Contains(99));
}
}
Output
True
True
False
2
True
False
How It Works
Type with one part.HashSet<int> means every item in the set is an int. Unlike a dictionary, there are no keys and values, only items.
Add tells you. The first Add(10) and Add(20) store new items and return True. The second Add(10) finds the item already there, stores nothing, and returns False.
No duplicates. Three Add calls were made, but Count is 2, because the set keeps each value once.
Fast question.Contains answers yes or no without looking at every item. 20 is in the set (True) and 99 is not (False).
Example 2 — Remove Duplicates from an Array
Pass an array with repeats to the HashSet constructor, then copy the unique items to a list and sort them for printing.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
int[] data = { 5, 3, 5, 1, 3, 3, 9 };
HashSet<int> unique = new HashSet<int>(data);
Console.WriteLine(data.Length);
Console.WriteLine(unique.Count);
List<int> sorted = new List<int>(unique);
sorted.Sort();
Console.WriteLine(string.Join(", ", sorted));
}
}
Output
7
4
1, 3, 5, 9
How It Works
Constructor does the work.new HashSet<int>(data) adds the array items one by one. Repeats are quietly ignored.
Seven in, four out. The array still has 7 items, but the set holds only the distinct values 5, 3, 1, and 9, so Count is 4.
Order is not promised. A HashSet does not guarantee the order of its items, so printing it directly could show any order.
Sort to print. The items are copied into a List<int> and sorted, so the output is always 1, 3, 5, 9.
Example 3 — Combine Two Sets
Start with {1, 2, 3} and {3, 4, 5}. Find the shared item with Overlaps, then merge them with UnionWith.
C#
using System;
using System.Collections.Generic;
class Program {
static string Show(HashSet<int> set) {
List<int> items = new List<int>(set);
items.Sort();
return "{" + string.Join(", ", items) + "}";
}
static void Main() {
HashSet<int> left = new HashSet<int> { 1, 2, 3 };
HashSet<int> right = new HashSet<int> { 3, 4, 5 };
Console.WriteLine(left.Overlaps(right));
left.UnionWith(right);
Console.WriteLine(Show(left));
Console.WriteLine(Show(right));
}
}
Output
True
{1, 2, 3, 4, 5}
{3, 4, 5}
How It Works
Two small sets. The collection initializer { 1, 2, 3 } fills each set when it is created. They share the number 3.
Overlaps asks.left.Overlaps(right) is True because at least one item (3) is in both. It changes nothing.
UnionWith changes left. It adds every item of right into left. The shared 3 is not doubled, so left becomes five items.
Right stays the same. Only the set you call the method on is changed. Show sorts the items first, so the printed order is always the same.
Continue
Next: C# HashSet Methods Index
After you know what a HashSet is for, open the method index for a full tutorial on each HashSet API.
It is a collection in System.Collections.Generic that stores unique items with no particular order. It can check whether an item exists very quickly.
A List keeps items in order by position and allows repeats, and Contains scans the list item by item. A HashSet keeps each item once, has no positions, and Contains is very fast on average.
No. Add returns false when the item is already in the set and the set does not change. Two items count as the same when Equals says so (or when the comparer you chose says so).
No. Do not rely on any order. Items may come out in the order you added them, but that is not guaranteed. Use SortedSet when you need sorted items, or copy to a List and sort it.
Open the C# HashSet Methods index. It lists Add, Remove, RemoveWhere, Clear, Contains, TryGetValue, the set operations, the set comparisons, capacity methods, CopyTo, and GetEnumerator.