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

Simple way to use LINQ with SharePoint ItemCollections

Here is a simple way to make use of LINQ with SharePoint item collections, for example, with List Items

SPListItemCollection listPages = pagesList.Items;
var latestPages = listPages.Cast<SPListItem>().Where(p => p.Name != defaultPageName);

And this becomes really cool if you use with Dynamic LINQ

var latestPages = listPages.Cast<SPListItem>()
                                .Where(p => p.Name != defaultPageName)
                                .OrderByDescending(p => p[Constants.Modified].ToString())
                                .Take(3);

How cool is that? :)


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.