There are many ways by which we can Iterate a HashSet.
So we have a HashSet with values, Tom, John and C#.
Now, let us see the first and easiest way to iterate a HashSet.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { var x = new HashSet<string>(); x.Add("Tom"); x.Add("John"); x.Add("C#"); foreach (var i in x) { System.Console.WriteLine(i); } } }
Similarly, in the above code we have created a HashSet.
var x = new HashSet<string>();
And initialised to the variable x.
In the next line we have used the foreach loop to Iterate through the HashSet.
foreach (var i in x) { System.Console.WriteLine(i); }
Now, if we see the iterations of for loop,
foreach (var i in x) { System.Console.WriteLine(i); }
In the first Iteration the first value of the HashSet x (i.e. Tom) is taken and put into the variable i.
And the print statement, prints the value of i.
Similarly, in the second Iteration the second value of the HashSet x (i.e. John) is taken and put into the variable i.
And the print statement, prints the value of i.
Similarly, in the third Iteration the third value of the HashSet x (i.e. C#) is taken and put into the variable i.
And the print statement, prints the value of i.