Domanda

I have a Sandbox webpart which retrieves a collection of Folders in a Library.

The library contains the following sample data:

|   Name        |   Created   |
-------------------------------
|    Folder 1   |  05/06/2013 |
|    Folder 2   |  07/08/2014 |
|    Folder 3   |  05/06/2015 |
|    Folder 4   |  04/03/2016 |
|    Folder 5   |  09/09/2016 |
|    ...        |    ...      |

I need retrieve these results ordered by Created field.


I have the following code for retrieve the collection of folders and sort its results:

string ImageLibrary = "GalleryLibrary";

// Get folders in the image library.
SPFolderCollection coleccionAlbums = (SPFolderCollection)_web.Folders[ImageLibrary].SubFolders;
List<SPFolder> spFolders = new List<SPFolder>();

// Create a new List<SPFolder> for store folders in DESCENDING order.
foreach (SPFolder fl in colAlbums) { spFolders.Add(fl); }

And I use any of the following code for order the elements in the list:

spFolders.Reverse();
// or
spFolders.Reverse(0, spFolders.Count);

However, the previous methods order the items by name, not by Date.

I make this change, but the Created property is not found:

spFolders.Sort((f1, f2) => f1.Item["Created"].ToString().CompareTo(f2.Item["Created"].ToString()));

How order a List of SPFolder by Created field?

È stato utile?

Soluzione

Using:

 using System.Linq;

Try this:

spFolders.OrderByDescending(f => f.Item[SPBuiltInFieldId.Created]);

or this (faster):

spFolders.OrderByDescending(f => f.Item.ID);

or this:

SPQuery query = new SPQuery();
query.Query = @"<Where>
                    <Eq>
                        <FieldRef Name='FSObjType' />
                        <Value Type='Integer'>1</Value>
                    </Eq>
                </Where>
                <OrderBy>
                    <FieldRef Name='Created' Ascending='False'/>
                </OrderBy>";

string ImageLibrary = "GalleryLibrary";
SPList list = _web.Lists.TryGetList(ImageLibrary);
if (list == null) return;

List<SPFolder> spFolders = new List<SPFolder>();
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
    spFolders.Add(item.Folder);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top