This post will discuss how to iterate over a HashSet<T> in C#.

The standard solution to iterate over the HashSet<T> object is using a foreach loop. The following example shows the usage of the foreach for printing the contents of a set.

Download  Run Code

Output:

1
2
3
4

 
Note that a HashSet<T> does not provide an indexer. That means a HashSet<T> maintains no particular order and the elements may come out in any order. If you need to maintain insertion order, consider using a List<T> instead. Also note that all the elements of a HashSet<T> are unique.

If you just need to print the string representation of a HashSet<T> instance, you may use:

Download  Run Code

That’s all about iterating over a HashSet<T> in C#.