Querying a SharePoint List with LINQ

I am continuously seeing the value in LINQ and I think with the upcoming changes in SharePoint 2010 I plan on making LINQ an even bigger part of my normal development practice.

First establish an SPList object of the list you would like to query data from.

SPList list = web.GetList("/Lists/ListUrl");

Next query the list; taking advantage of the filtering and sorting capabilities built into LINQ

var listItems = from SPListItem item in list.Items
                            orderby item.Title
                            ascending
                            select item;

And with a where query utilizing a custom field!

var listItems = from SPListItem item in list.Items
                            orderby item.Title
                            ascending
                            where ((DateTime)item["CustomExpirationField"]).DayOfYear >= DateTime.Now.DayOfYear
                            select item;

Now feel free to loop through your data and take care of business!

foreach (SPListItem item in listItems)
{
     // item.Title
     //etc
}
I'm a public speaker and the Chief SharePoint Architect for Eastridge, a Microsoft Gold Partner specializing in SharePoint and custom application development in Winston-Salem, NC. I focus on the SharePoint platform with a specialty in Information Architecture, Publishing and Best Practices.

Got something to say? Go for it!