-3

I am little bit confused about loops in C#, What is best use cases for various loops like For, foreach, while, do while, List.ForEach?

Mukesh
  • 360
  • 4
  • 12

2 Answers2

0

Depends on the usecase. For example, if you want only the odd indexed items in an array, use a for loop with +2 in each run. ForEach is suitable for standard loops. But in some cases you cannot use one of them, e.g. in a foreach you cannot delete items from the collection. You need e.g. for in this case. And, when you have a specific condition, you need a while loop.

Boland
  • 1,340
  • 1
  • 11
  • 32
0

You use for loop when you wanted to set a counter iteration such

for(int i=0;i<3;i++)//will loop until it meets the condition i<3
{ //statement here}

You use foreach if you are going to loop and display the collection of a variable such

string[] name = { "josh", "aj", "beard" };

    // ... Loop with the foreach keyword.
    foreach (string value in name)
    {
        Console.WriteLine(name);
    }

while is use if you want to meet the condition first before the statement

while(condition)
{
//statement here
}

do while is use if you want to do the statement first before the condition

do
{
//statement here
}
while(condition)
Rairulyle
  • 1
  • 1
  • 1
  • 4