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

0 votes
49 views
Ethan Karla asked 25 days ago in programming by Ethan Karla

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

1 Answer

0 votes
Ravi Vishwakarma answered 19 days ago by Ravi Vishwakarma
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#.