Blog from Saravanan Arumugam

Let us talk about Technologies

Index in IEnumerable

When we use the IEnumerable interface, its usually hard to get the index of the item.

For example, I need to display a dropdown list in a page that uses MVC 3. I can use the CurrentCulture class to get the array of month names. But I want to set the integer as the value representing the month.

<select id="MonthSelection" name="MonthSelection">
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>
    <option value="4">Apr</option>
    <option value="5">May</option>
    <option value="6">Jun</option>
    <option value="7">Jul</option>
    <option value="8">Aug</option>
    <option value="9">Sep</option>
    <option value="10">Oct</option>
    <option value="11">Nov</option>
    <option value="12">Dec</option>
    <option value="13"></option>

The choice I had was this. I couldn’t use the foreach since it would not provide me the ability to get the index of the item. So I am left with for() loop. However, look at the code below, isn’t that too much of coding for a simple thing?

Dictionary<int, string> months = new Dictionary<int, string>();

for (int index = 0;

    index < CultureInfo.CurrentCulture





    months.Add(index + 1,






Using the for() loop is not comfortable all the time.



Linq provides a solution to this situation. In a IEnumerable, if you want the index of the item, use the projection (Select) with a second parameter to the lambda expression. The second parameter is usually the index of the item in the collection.

.AbbreviatedMonthNames.Select((month, index) 
           => new { Key = index + 1, Value = month })

Now the whole code show on the previous example is shrunk to a single line. Isn’t that great from Linq?


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

%d bloggers like this: