Get the First & Last ListItem in Sharepoint List

后端 未结 2 1324
小鲜肉 2021-02-20 17:08

On a pageLoad event I want to go to two different SharePoint Lists and get the first ListItem from one list and an the last ListItem in another. I don\'t know any o

  • 2021-02-20 17:31

    You can try this to get the last itemID

    SPWeb web = SPContext.Current.Web;
                SPList List = web.Lists[ListName];
                int itemId = List.Items[List.ItemCount - 1].ID;


    0 讨论(0)
  • 2021-02-20 17:48

    The condition "first item" and "last item" is not very clear. Assuming you want to retrieve the first and the latest created item. Important to note is that retrieving items via the index of the SPListItemCollection can be slow for large lists since accessing SPList.Items returns all items of the list. That's why I suggest using a CAML query:

    SPList list = // some list;
    SPQuery query = new SPQuery();
    query.RowLimit = 1;
    query.Query = "<OrderBy><FieldRef Name='ID' /></OrderBy>";
    return list.GetItems(query).Cast<SPListItem>().FirstOrDefault();

    For the "last item" you have to reverse the ordering:

    <OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>

    If you want to get the last and the first item based on another condition you just have to change the order by field.

    Even better would be to order by the ID field. With that you could achieve the same result. Not only better, the created field could have been changed through code as pointed out by @Kobi.

    0 讨论(0)