What are the uses of forEach loop in C#? how to fetch a value from list collection in C#.

Asked 25-Aug-2021
Viewed 729 times

1

What are the uses of forEach loop in C#? how to fetch a value from list collection in C#.


2 Answers


0

In C#, the foreach loop iterates collection types such as Array, ArrayList, List, Hashtable, Dictionary, etc. It can be used with any type that implements the IEnumerable interface.

Syntax:

foreach (var item in collection)
{
	//access item														
}

The following example demonstrates iteration of an array using a foreach loop.

Example: Iterate an Array

 Copy

string[] carCompanies = { 'Tata Motors', 'Mahindra', 'Volkswagen', 'Toyota' };
																
foreach(string car in carCompanies)
{
	Console.WriteLine('{0}', car);
} 

 

Output:

Tata Motors
Mahindra
Volkswagen
Toyota

The following example demonstrates the foreach loop on a list collection.

Example: Iterate a List

List<int> oddNumbers = new List<int>() { 1, 3, 5, 7, 9};
																
foreach(int num in oddNumbers)
{
	Console.Write(num);
}

oddNumbers.ForEach(num => Console.Write(num)); //using ForEach extension method

Output.

13579

The System.Collections.Generic namespace contains the ForEach() extension method that can be used with any built-in collection classes such as List, Dictionary, SortedList, etc.

Important Points:

  • The foreach loop iterate only in forward direction.
  • Performance wise foreach loop takes much time as compared with for loop. Because internally it uses extra memory space as well as.
  • The foreach loop use GetEnumarator() method of the IEnumerable interface. So, the foreach loop can be used with any class that has implemented the interface.
  • Exit the foreach loop by using break, return, Goto and throw.

The following example demonstrates the foreach loop on a dictionary collection.


1

Foreach Loop in C#: Foreach Loop provides us the facility to access all the elements of an array sequentially. This loop is also used to sequentially assess all the elements of other types of .NET Collection Types, which we will understand later. This new Construct has been added to access the Elements of Collection and Array in C#. This construct can be used in two ways as follows:
Syntax
foreach( Type Identifier in ArrayName) { 
//Statements
}
foreach( var Identifier in ArrayName) {
//Statements
}
In this Construct, ArrayName is the Array, all the elements of which are to be accessed sequentially while Type or var represents the type of the elements of that Array and Retrieved Values ​​from Array are obtained in One by One Identifier. The foreach loop continues to iterate until all the elements of the array or collection are accessed. We can access and manipulate different elements of the array using this loop.
Example 
using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThreadDemo
{
    class ForEachLoopDemo
    {
        List<int> list;
        public ForEachLoopDemo()
        {
            list = new List<int>();
            this.AddDataIList();
        }
        private void AddDataIList()
        {
            int[,] array = new int[,] { { 10,20,30,40,50},{100,200,300,400,500} };
            foreach (int item in array)
            {
                list.Add(item);
            }
        }
        public void PrintListData()
        {
            foreach (int item in list)
            {
                Console.Write(item+ ' ');
            }
        }
        public static void Main(string[] args)
        {
           ForEachLoopDemo foreachlopp = new ForEachLoopDemo();
           foreachlopp.PrintListData();
        }   
     }
}

Output:
What are the uses of forEach loop in C#? how to fetch a value from list collection in C#.