Iterate over a HashSet in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 4 }; foreach (var item in numbers) { Console.WriteLine(item); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 4 }; Console.WriteLine(String.Join(", ", numbers)); // 1, 2, 3, 4 } } |
That’s all about iterating over a HashSet<T> in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)