C# HashSet
last modified November 6, 2026
In this article we show how to work with a HashSet collection in C#.
HashSet
HashSet<T> represents a set of values. It contains no duplicate
elements. The collection models the mathematical set abstraction. It lives
in the System.Collections.Generic namespace, which is imported
implicitly in modern .NET projects.
The set is backed by a hash table. Adding, removing, and looking up an
element are O(1) operations on average. This makes a
HashSet a much better choice than a List when we
frequently ask whether a value is present.
HashSet does not guarantee any ordering of elements. The
iteration order may look like insertion order for small sets, but we must
not rely on it; it can change after removals. If we need to maintain sorted
order, we can use the SortedSet collection.
C# HashSet count elements
The Count property returns the number of elements in the
HashSet.
var brands = new HashSet<string>();
brands.Add("Wilson");
brands.Add("Nike");
brands.Add("Volvo");
brands.Add("IBM");
bool added = brands.Add("IBM");
Console.WriteLine($"IBM added again: {added}");
int nOfElements = brands.Count;
Console.WriteLine($"The set contains {nOfElements} elements");
Console.WriteLine(string.Join(", ", brands));
We have a set of brands. The IBM string is added twice, but
the set stores it only once.
var brands = new HashSet<string>();
A new empty HashSet is created.
brands.Add("Wilson");
Elements are added to the set with the Add method.
bool added = brands.Add("IBM");
The Add method returns false if the element is
already present in the set.
int nOfElements = brands.Count;
We get the number of elements with the Count property.
$ dotnet run IBM added again: False The set contains 4 elements Wilson, Nike, Volvo, IBM
C# HashSet initialization
A set can be created with a collection initializer, a collection expression,
from an existing collection, or with the LINQ ToHashSet method.
Duplicates are silently dropped in all cases.
HashSet<int> vals = [1, 2, 3, 3, 2, 1, 4];
Console.WriteLine(string.Join(", ", vals));
var words = new HashSet<string> { "sky", "cup", "sky", "pen" };
Console.WriteLine(string.Join(", ", words));
int[] nums = [7, 7, 8, 9, 9, 9];
HashSet<int> unique = nums.ToHashSet();
Console.WriteLine(string.Join(", ", unique));
var colours = new HashSet<string>(["red", "green", "red", "blue"]);
Console.WriteLine(colours.Count);
We create four sets in different ways.
HashSet<int> vals = [1, 2, 3, 3, 2, 1, 4];
Since C# 12 we can use a collection expression to initialize a set. The target type must be stated explicitly.
HashSet<int> unique = nums.ToHashSet();
The ToHashSet method creates a set from any
IEnumerable<T>. It is a quick way to remove duplicates
from an array or a list.
var colours = new HashSet<string>(["red", "green", "red", "blue"]);
The constructor accepts an existing collection whose elements are copied into the new set.
$ dotnet run 1, 2, 3, 4 sky, cup, pen 7, 8, 9 3
C# HashSet removing elements
In the next example, we remove elements from a HashSet.
var brands = new HashSet<string>
{
"Wilson", "Nike", "Volvo", "Kia", "Lenovo"
};
Console.WriteLine(string.Join(", ", brands));
brands.Remove("Kia");
brands.Remove("Lenovo");
bool removed = brands.Remove("Apple");
Console.WriteLine($"Apple removed: {removed}");
Console.WriteLine(string.Join(", ", brands));
brands.Clear();
if (brands.Count == 0)
{
Console.WriteLine("The brands set is empty");
}
var words = new HashSet<string>
{
"sky", "blue", "cup", "cold", "cloud", "pen", "bank"
};
int n = words.RemoveWhere(word => word.Length == 3);
Console.WriteLine($"{n} words removed");
Console.WriteLine(string.Join(", ", words));
The elements are removed with Remove, Clear, and
RemoveWhere.
brands.Remove("Kia");
A single element is removed with Remove.
bool removed = brands.Remove("Apple");
The method returns false if the element was not found.
brands.Clear();
All elements are removed with Clear.
int n = words.RemoveWhere(word => word.Length == 3);
With RemoveWhere, we remove elements that satisfy the given
predicate. The method returns the number of removed elements.
$ dotnet run Wilson, Nike, Volvo, Kia, Lenovo Apple removed: False Wilson, Nike, Volvo The brands set is empty 3 words removed blue, cold, cloud, bank
C# HashSet loop
We can loop over a HashSet with foreach and
while keywords.
var words = new HashSet<string>
{
"sky", "blue", "cup", "cold", "cloud", "pen", "bank"
};
foreach (var word in words)
{
Console.WriteLine(word);
}
Console.WriteLine("----------------------");
using var it = words.GetEnumerator();
while (it.MoveNext())
{
Console.WriteLine(it.Current);
}
In the example, we iterate over a HashSet of words with
foreach and while.
using var it = words.GetEnumerator();
while (it.MoveNext())
{
Console.WriteLine(it.Current);
}
The GetEnumerator method returns an enumerator. The
MoveNext method advances it to the next element and the
Current property returns the element at the current position.
The enumerator is disposable, so we declare it with using.
This is what the foreach loop does for us behind the scenes.
$ dotnet run sky blue cup cold cloud pen bank ---------------------- sky blue cup cold cloud pen bank
C# HashSet Contains
The Contains method determines whether a HashSet
contains the specified element.
var words = new HashSet<string>
{
"sky", "blue", "cup", "cold", "cloud", "pen", "bank"
};
Console.WriteLine(words.Contains("sky"));
Console.WriteLine(words.Contains("water"));
Console.WriteLine("-----------------");
var users = new HashSet<User>
{
new("John Doe", "gardener"),
new("Roger Roe", "driver"),
new("Lucy Smith", "teacher")
};
var u1 = new User("John Doe", "gardener");
var u2 = new User("Jane Doe", "student");
Console.WriteLine(users.Contains(u1));
Console.WriteLine(users.Contains(u2));
record User(string Name, string Occupation);
We have two HashSet collections.
Console.WriteLine(words.Contains("sky"));
Console.WriteLine(words.Contains("water"));
We check if a HashSet of words contains the two specified
words.
var u1 = new User("John Doe", "gardener");
var u2 = new User("Jane Doe", "student");
Console.WriteLine(users.Contains(u1));
Console.WriteLine(users.Contains(u2));
The u1 object is a different instance than the one stored in the
set. A C# record contains a compiler-generated, value-based implementation of
the Equals and GetHashCode methods; therefore, the
Contains method works as we would expect.
$ dotnet run True False ----------------- True False
C# HashSet with custom class
A class uses reference equality by default. Two different instances with the
same data are not equal. To use a class in a HashSet with
value semantics, we need to override the Equals and the
GetHashCode methods.
var users = new HashSet<User>
{
new("John Doe", "gardener"),
new("Roger Roe", "driver"),
new("Lucy Smith", "teacher")
};
var u1 = new User("John Doe", "gardener");
var u2 = new User("Jane Doe", "student");
Console.WriteLine(users.Contains(u1));
Console.WriteLine(users.Contains(u2));
class User(string name, string occupation)
{
public string Name { get; } = name;
public string Occupation { get; } = occupation;
public override bool Equals(object? obj)
{
return obj is User user &&
Name == user.Name &&
Occupation == user.Occupation;
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Occupation);
}
}
In this example, we have a HashSet of user objects. Since the
type is defined with the class keyword, we add the implementation
of the Equals and GetHashCode methods.
public override int GetHashCode()
{
return HashCode.Combine(Name, Occupation);
}
The HashCode.Combine method computes a hash code from several
values. Equal objects must produce equal hash codes; the set first uses the
hash code to find a bucket and only then calls Equals.
$ dotnet run True False
C# HashSet custom comparer
The equality of elements can be customized by passing an
IEqualityComparer<T> to the constructor.
var langs = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"C#", "Python", "python", "Go", "PYTHON", "go"
};
Console.WriteLine(string.Join(", ", langs));
Console.WriteLine(langs.Contains("c#"));
if (langs.TryGetValue("GO", out string? actual))
{
Console.WriteLine($"Stored value: {actual}");
}
We create a case-insensitive set of strings.
var langs = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
The StringComparer.OrdinalIgnoreCase comparer treats strings
that differ only in case as equal. The first added variant is kept.
if (langs.TryGetValue("GO", out string? actual))
The TryGetValue method searches for a value and returns the
equal value actually stored in the set.
$ dotnet run C#, Python, Go True Stored value: Go
C# HashSet set operations
HashSet contains a set of methods specific to a set. These
methods modify the set in place.
HashSet<int> vals1 = [1, 2, 3, 4, 5];
HashSet<int> vals2 = [6, 7, 8, 9, 10];
vals1.UnionWith(vals2);
Console.WriteLine(string.Join(", ", vals1));
HashSet<int> vals3 = [1, 2, 3, 4, 5];
HashSet<int> vals4 = [3, 4, 5, 6, 7];
vals3.IntersectWith(vals4);
Console.WriteLine(string.Join(", ", vals3));
HashSet<int> vals5 = [1, 2, 3, 4, 5];
vals5.ExceptWith(vals4);
Console.WriteLine(string.Join(", ", vals5));
HashSet<int> vals6 = [1, 2, 3, 4, 5];
vals6.SymmetricExceptWith(vals4);
Console.WriteLine(string.Join(", ", vals6));
We use UnionWith, IntersectWith,
ExceptWith, and SymmetricExceptWith methods.
vals1.UnionWith(vals2);
The UnionWith method modifies the HashSet object to
contain elements from both sets.
vals3.IntersectWith(vals4);
The IntersectWith method modifies the HashSet object
to contain only elements that are present in both collections.
vals5.ExceptWith(vals4);
The ExceptWith method removes all elements that are present in
the other collection. This is the set difference.
vals6.SymmetricExceptWith(vals4);
The SymmetricExceptWith method keeps elements that are present
in one of the collections but not in both. Notice that the result is not
ordered.
$ dotnet run 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 3, 4, 5 1, 2 1, 2, 7, 6
C# HashSet set relations
Several methods test the relation between two sets. They return a boolean value and do not modify the set.
HashSet<int> all = [1, 2, 3, 4, 5, 6]; HashSet<int> evens = [2, 4, 6]; HashSet<int> odds = [1, 3, 5]; HashSet<int> small = [1, 2, 3]; Console.WriteLine(evens.IsSubsetOf(all)); Console.WriteLine(all.IsSupersetOf(odds)); Console.WriteLine(evens.IsProperSubsetOf(evens)); Console.WriteLine(evens.Overlaps(odds)); Console.WriteLine(small.Overlaps(odds)); Console.WriteLine(small.SetEquals([3, 2, 1, 1]));
The IsSubsetOf method checks whether all elements of the set
are contained in the other collection; IsSupersetOf is the
opposite check. A proper subset must also be smaller than the other set,
which is why a set is not a proper subset of itself. Overlaps
determines whether the two collections share at least one element and
SetEquals whether they contain the same elements, ignoring
order and duplicates.
$ dotnet run True True False False True True
C# SortedSet
The SortedSet represents a set of objects that is maintained in
sorted order. It is implemented as a balanced binary tree, so its operations
are O(log n).
var vals = new SortedSet<int> { 5, 2, 1, 4, 3, 7, 6 };
Console.WriteLine(string.Join(", ", vals));
Console.WriteLine($"Min: {vals.Min}, Max: {vals.Max}");
Console.WriteLine(string.Join(", ", vals.GetViewBetween(3, 5)));
var words = new SortedSet<string>
{
"sky", "blue", "cup", "cold", "cloud", "pen", "bank"
};
Console.WriteLine(string.Join(", ", words));
var users = new SortedSet<User>
{
new("Robin", "bookseller"),
new("John", "gardener"),
new("John", "writer"),
new("Janet", "teacher"),
new("Andrew", "driver"),
new("Lucy", "accountant")
};
Console.WriteLine(string.Join("\n", users));
record User(string Name, string Occupation) : IComparable<User>
{
public int CompareTo(User? other) =>
string.Compare(Occupation, other?.Occupation, StringComparison.Ordinal);
}
We have SortedSet of integers, strings, and users.
Console.WriteLine($"Min: {vals.Min}, Max: {vals.Max}");
Console.WriteLine(string.Join(", ", vals.GetViewBetween(3, 5)));
The Min and Max properties return the smallest and
largest values. The GetViewBetween method returns a subset
within the given range.
record User(string Name, string Occupation) : IComparable<User>
{
public int CompareTo(User? other) =>
string.Compare(Occupation, other?.Occupation, StringComparison.Ordinal);
}
The users are sorted by their occupation. To be stored in a
SortedSet, a type must implement IComparable<T>
or we must provide an IComparer<T>. Note that elements that
compare as equal are treated as duplicates; two users with the same
occupation could not both be stored.
$ dotnet run
1, 2, 3, 4, 5, 6, 7
Min: 1, Max: 7
3, 4, 5
bank, blue, cloud, cold, cup, pen, sky
User { Name = Lucy, Occupation = accountant }
User { Name = Robin, Occupation = bookseller }
User { Name = Andrew, Occupation = driver }
User { Name = John, Occupation = gardener }
User { Name = Janet, Occupation = teacher }
User { Name = John, Occupation = writer }
Source
HashSet class - language reference
In this article we have worked with C# HashSet.
Author
List all C# tutorials.