C#: Get Index value in foreach Loop of IEnumerable

visibility 152 access_time 5 months ago languageEnglish

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 Select LINQ extension method.

Output:

000 - Hello
001 - World
002 - !
info Last modified by Raymond 5 months ago copyright This page is subject to Site terms.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

timeline Stats
Page index 1.19
More from Kontext
Convert string to date in C# / .NET Framework
visibility 264
thumb_up 0
access_time 2 years ago
[C#] Connect to Teradata Database via .NET Data Provider
visibility 10,467
thumb_up 0
access_time 3 years ago
Apache Ignite Installation on Windows
visibility 177
thumb_up 0
access_time 5 months ago