All posts tagged LINQ

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
}