SPListItem

brendanlefavre
brendanlefavre used Ask the Experts™
on
How can I get the last entry in a list? The example below will gain me access to the items in a list, but I'm getting stuck on how to get the last item submitted.

using (SPSite siteCol = new SPSite("http://server/sites/Contoso"))
{
    using (SPWeb web = siteCol.RootWeb)
    {
        SPList list = web.GetList("/sites/Contoso/Lists/Books");
        SPListItemCollection items = list.GetItems("Title", "LogIDNumber",);
    }
}

Open in new window


Cheers,
Brendan
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2011

Commented:
Use a CAML query to get the items and get the last item in the result.

<Query>
    <OrderBy>
            <FieldRef Name="LogIDNumber" Ascending="FALSE" />
    </OrderBy>
</Query>


If you  want the last modified/created  item, you can also use the modified/created by field
Jamie McAllisterCloud Expert
Most Valuable Expert 2013
Top Expert 2014

Commented:
Something like this should do it.
SPQuery query = new SPQuery();
 query.Query = "<OrderBy><FieldRef Name='Created'
Ascending='FALSE' /></OrderBy>";
query.RowLimit = 1;
SPListItemCollection col = myList.GetItems(query);
                           
if (col.Count > 0)
{
  //do something
}

Open in new window

Hi!
You can simply do it like this:
SPListItem lastItem = list.Items[list.Items.Count -1];

But this is only suitable for small lists, if you have large list (more than 2000 item) you should use SPQuery instead of working with Items collections (because your code will be slow otherwise)

SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\""; // if you want to get data from all folder
query.Query = "<OrderBy><FieldRef Name='ID'  Ascending="FALSE"/></OrderBy>";
SPListItemCollection items = myList.GetItems(query);
SPListItem item = items.Count > 0 ? items[0] : null;

For more information on quering items with SPQuery look my blog (http://www.spsamples.com/2011/06/sharepoint-caml-queries-samples.html)

Author

Commented:
this helped me resolve my issue

Cheers,
Brendan

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial