Reputation: 25
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
}
}
}
Upvotes: 1
Views: 510
Reputation: 2364
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.
Upvotes: 1
Reputation: 112
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.
Upvotes: 1
Reputation: 3594
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
}
}
Upvotes: 2
Reputation: 50104
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
(i.e. call FItem.Items[i]
repeatedly) you end up querying the list repeatedly, so don't do that.
Upvotes: 2