C#: Get Index value in foreach Loop of IEnumerable

Raymond Tang Raymond Tang 1 3683 2.89 index 12/28/2021

In C#, we can use foreach to loop enumerable variables. For example the following code snippet loops through the string enumerable:

var items = new []{"Hello","World","!"} as IEnumerable<string>;foreach(var item in items)    Console.WriteLine(item);

In some scenarios, it might be helpful to get the index too. This code snippet shows one approach to implement that.

Code snippet

var items = new []{"Hello","World","!"} as IEnumerable<string>;foreach(var (item, i) in items.Select((item, i)=> (item, i)))    Console.WriteLine("{0:000} - {1:%s}", i, item);

The above code snippet utilize SelectLINQ extension method.

Output:

000 - Hello

001 - World

002 - !

c#

Join the Discussion

View or add your thoughts below

Comments