Friday 12 April 2013

Getting the First or Last element of a list in Sharepoint 2013 (2010 compatible) using the object model.

This is one of the missing commands in Sharepoint, get the first and the last element of a list really quickly. There is a way, of doing it with LINQ, but the performance is ridiculous, you don’t really want to go for the LINQ route.

What are the alternatives for this issue? well, we all know CAML is the fastest way, outside SQL to get data from Sharepoint, so let’s go to do it like this.

To get the last element of the list (in this case Title):

SPQuery query = new SPQuery();
query.RowLimit = 1;
query.Query = "<OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>";
SPListItemCollection listItemCollection = _spList.GetItems(query);
//## GETTING THE LAST ITEM TO GET THE ID
if (listItemCollection.Count > 0)
{
      if (listItemCollection[0]["Title"] != null)
      {
             _iTitle = Convert.ToInt32(listItemCollection[0]["Title"]);
             _iTitle++;
      }                            
}

To get the first element of the list (in this case Title):
SPQuery query = new SPQuery();
query.RowLimit = 1;
query.Query = "<OrderBy><FieldRef Name='ID' /></OrderBy>";
SPListItemCollection listItemCollection = _spList.GetItems(query);
//## GETTING THE LAST ITEM TO GET THE ID
if (listItemCollection.Count > 0)
{
    if (listItemCollection[0]["Title"] != null)
    {
        _iTitle = Convert.ToInt32(listItemCollection[0]["Title"]);
        _iTitle++;
    }                            
}

Conclusion: CAML still the fastest way to do queries in Sharepoint, just use your imagination and go for it!

2 comments: