简体   繁体   中英

reverse an SPlist

I need to extract the items from a list in reverse order (from last entry to the first). I've managed to get all the items but, from the first to the last. Here is part of the code I am using:

The List is on a different site collection.

     using (SPSite oSite = new SPSite("urltolist"))
        {

            using (SPWeb oWeb = oSite.RootWeb)
            {
                SPList FItem = oWeb.Lists["List"];



                foreach (SPListItem item in FItem.Items)             
                {
                 //Display entries
                }
             }
       }

Get the SPListItemCollection , then iterate through it in reverse:

var itemCollection = FItem.Items;
for(int i = itemCollection.Count - 1; i >= 0; i--)
{
    var item = itemCollection[i];
    //Display entries
}

If you just iterate over FItem.Items (ie call FItem.Items[i] repeatedly) you end up querying the list repeatedly, so don't do that.

You don't need to dispose of the RootWeb in this case.

using(var site = new SPSite("urltolist"))
{
    var list = site.RootWeb.Lists["List"];
    foreach(var li in list.Items.Cast<SPListItem>().Reverse().ToList())
    {
        // Display entries
    }
}

The question you need to ask is what order the items are to begin with - the way you do it, they'll be sorted by ID (analogous to time of creation). If you want to sort them in another way, use an SPQuery with an OrderBy clause to retrieve the list items.

this can also be accomplished with a CAML Query. Do you need to return ALL items? If you can limit the query you can use the CAML node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM