Direct Linq to SPListItemCollection
Posted January 3, 2008on:
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]);
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