Use LINQ with SharePoint itemCollections

The common code to get data by itemcollections is by using SPListitems and using SPQuery for the query the data.

The common code is like this below :

SPWeb web = SPContext.Current.Web;

SPList list = web.List(“name of list”);

SPQuery  query = new SPQuery (“xxx caml xxx”);

SPListItemCollection itemcols = list.getItems(query);

After this we can iterate using foreach or for to get data from itemscols.

But now we also can achieve this code with LINQ way and here as below the sample code :

SPListItemCollection itemcols = list.Items;
var latestItems = itemcols.Cast<SPListItem>().Where(p => p.Title != testTitle);

or you can also do like this as well :

var latestItems = itemcols.Cast<SPListItem>()
.Where(p => p.Title != testTitle)
.OrderByDescending(p => p[Constants.Modified].ToString())

Cool right! 🙂

Happy Sharepoint-ing


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.