how i can start foreach loop with customize index in c# code example

Example 1: how to get foreach index c#

// foreach with a "manual" index
int index = 0;
foreach (var item in collection)
{
    DoSomething(item, index);
    index++;
}

// normal for loop
for (int index = 0; index < collection.Count; index++)
{
    var item = collection[index];
    DoSomething(item, index);
}

Example 2: foreach index start from at 1 in c#

int i = -1;
foreach (Widget w in widgets)
{
   i++;
   // do something
}

Tags:

Misc Example