How use indexer with foreach loop in C#

If you really don’t like construct to get the current index of step in iteraction like this one:

int index = 0;
foreach (Object o in collection)

I will try show you a few possible better looking equivalents. Of course wording “better looking” is dependent of each individual view. Rate it yourself:

string[] tab = new string[] { "one", "two", "three" };

foreach (var o in tab.Select((x, i) => new { x, i }))
   Console.WriteLine("{0} {1}", o.i, o.x);

How it works?
Foreach instruction is  for iterating over collections that implement IEnumerable. There is calling GetEnumerator() method on the collection which return an Enumerator. In this approach we wrap each item of the collection in an anonymous object that knows the index.

In this example above I have used an array, but according to description of course you can use any other type which implement IEnumerable. So this solution is also applicable for a list, for example:

List<string> list = new List<string>();

foreach (var o in list.Select((x, i) => new { x, i }))
    Console.WriteLine("{0} {1}", o.i, o.x);

Please leave any comments if you enjoy it!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s