Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - ITERATING HASHSET


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.


Iterating a HashSet using for loop


Example :



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);  
        }
    }    
}


Output :



  Tom
  John
  C#

Similarly, in the above code we have created a HashSet.


var x = new HashSet<string>();

And initialised to the variable x.

C_Sharp

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);
}

1st Iteration


In the first Iteration the first value of the HashSet x (i.e. Tom) is taken and put into the variable i.

C_Sharp

And the print statement, prints the value of i.

Output :



  Tom

2nd Iteration


Similarly, in the second Iteration the second value of the HashSet x (i.e. John) is taken and put into the variable i.

C_Sharp

And the print statement, prints the value of i.

Output :



  Tom
  John

3rd Iteration


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.

Output :



  Tom
  John
  C#