Getting Index from a foreach loop

With a little help of Linq, we can get the index from a foreach loop, eg:

foreach (var item in MyListing.Select((value, idx) => new { idx, value }))
{
Console.WriteLine($"{item.idx}: {item.value}");
}

This can be even written as extension like below :

public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self) => self?.Select((item, index) => (item, index)) ?? new List<(T, int)>();

You can then use it as follow

foreach (var (item, idx) in MyListing.WithIndex()
{
Console.WriteLine($"{item}: {idx}");
}
By using our website you are consenting to our use of cookies to ensure you get the best experience on our website. Learn more