Getting the index of an item in a LINQ query

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

Feb 11 Vahokif

Vahokif

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

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading





Creative Commons License
Chaks' Corner Blog by Chakkaradeep Chandran is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
Based on a work at www.chakkaradeep.com.
Permissions beyond the scope of this license may be available at http://www.chakkaradeep.com.