Getting the index of an item in a LINQ query

by Chakkaradeep 4. June 2009 11:41

So, you want to retrieve the index of an matching item in an array or a collection and you want to use LINQ.

For example, I want to get the month number given the month name – If I pass 3, I should get March

Of course, you could write your own enum and other stuffs, but there is already an out-of-the-box MonthNames array that we can make use of.

foreach(string month in CultureInfo.CurrentCulture.DateTimeFormat.MonthNames)
{
   Console.WriteLine("Month: " + month);
}

 

How can we make use of this MonthNames array to get the month name based on the month number?

Using LINQ, its very simple!

int nMonth = 1;
 
var selectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
                    .Where((month, index) => index == (nMonth-1))
                    .FirstOrDefault();
Console.WriteLine(selectedMonth);

The lambda expression (month,index) with 2 parameters gets the index of that item and it is an inbuilt feature in LINQ. The second parameter always refers to the index of that item. It is also not necessary that it should be named index. You can name it anything you want, like this:

var selectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
                    .Where((month, month_index) => month_index == (nMonth - 1))
                    .FirstOrDefault();

Comments

2/11/2010 2:43:53 AM #

Vahokif

This is getting an item given an index, and you can do it much simpler with IEnumerable<T>.ElementAt.

Vahokif Hungary | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About the author




NZ SharePoint Conference 2010

 

 

New Zealand SharePoint User Group