C# go through list by index code example
Example 1: how to get foreach index c#
int index = 0;
foreach (var item in collection)
{
DoSomething(item, index);
index++;
}
for (int index = 0; index < collection.Count; index++)
{
var item = collection[index];
DoSomething(item, index);
}
Example 2: get both item and index in c#
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source)
{
return source.Select((item, index) => (item, index));
}
foreach (var (item, index) in collection.WithIndex())
{
DoSomething(item, index);
}