Technical Fun

Direct Linq to SPListItemCollection

Posted on: January 3, 2008

This one’s a sequel to my last post about LINQ-ize a SPListCollection.
I got another not-so-important urge to get a maximum number from one of my custom list’s field.
Let’s just say the the field containing the number is “Document Number”, and I want to grab the current maximum value of that field to do various purposes.

Now, as I am a little bit obsessed with Linq, so let’s leave CAML behind and grab Linq instead.
Let’s begin by creating a wrapper around SPListItemCollection object to make it Linq-able (just like I did with the SPListCollection).

public class SPListItemCollectionAdapter : List<SPListItem>
private SPListItemCollection _listItemCollection;

public SPListItemCollectionAdapter(SPListItemCollection listItemCollection)
_listItemCollection = listItemCollection;


private void Refresh()

foreach (SPListItem item in _listItemCollection)


then voila!, you can use Linq’s aggregation function to grab the max value currently on a field called “Document Number” inside a list called “Document”. Write a method that might look like this:

private static double GetMaxFrom(string listname, string fieldname)
SPListItemCollection itemcol = mossWeb.Lists[listname].Items;
SPListItemCollectionAdapter itemsAdapter = new SPListItemCollectionAdapter(itemcol);
var result = itemsAdapter.Max(x => x[fieldname]);
return (double)result;

mossWeb is just a singleton for the SPWeb object, as I was using it numerous times on other methods as well.
I also took the liberty of using the lambda expression (x => x[fieldname]) just to evaluate the specific field.
Using it is as easy as calling GetMaxFrom("Document","Document Number");


3 Responses to "Direct Linq to SPListItemCollection"


I saw your comment about mossweb singleton.
It seems a great idea in order to reduce the numer of spweb in a page.

Would you mind to share that code?

Kind Regards

Rather than build an adapted list, you should use Cast():

var itemsAdapter = itemCol.Cast();
var result = itemsAdapter.Max(x => x[fieldname]);
return (double)result;

Or use ‘yield return’:

Cheers ~

I just noticed WordPress ate the type specifier. It should be…
var itemsAdapter = itemCol.Cast<SPListItem%gt;();

Leave a Reply

Please log in using one of these methods to post your comment: 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

%d bloggers like this: