What are the uses of forEach loop in C#? how to fetch a value from list collection in C#.
What are the uses of forEach loop in C#? how to fetch a value from list collection in C#.
2 Answers
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 theIEnumerableinterface. 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.
foreach( Type Identifier in ArrayName) {
//Statements
}
foreach( var Identifier in ArrayName) {
//Statements
}
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();
}
}
}
