in SharePoint, SharePoint 2007

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();

Write a Comment

Comment

Time limit is exhausted. Please reload the CAPTCHA.