Search code examples
c#asp.netsharepointcsomcaml

CSOM CAML Query order by list item collection file properties


How would I update the following code to order by ListItemCollection.File.Name or other File properties?

using (ClientContext spClientContext = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, _clientId, _clientSecret))
{
    if (spClientContext != null)
    {

        CamlQuery camlQuery = new CamlQuery();

        camlQuery.FolderServerRelativeUrl = getSiteUrlAbsolutePath(siteUrl) + "/Shared Documents/" + folderPath;

        
        camlQuery.ViewXml = "<View Scope="RecursiveAll">" +
            "<Query>" +
            "<Where>" +
            "<Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq>" +
            "</Where>" +
            "<OrderBy><FieldRef Name=\"item.File.Name\" Ascending=\"FALSE\"/></OrderBy>" +
            "</Query>" +
            "</View>";

        List list = spClientContext.Web.Lists.GetByTitle("Documents");

        ListItemCollection listItems = list.GetItems(camlQuery);

        spClientContext.Load(listItems,
                             items => items.Include(
                                 item => item.DisplayName,
                                 item => item.FileSystemObjectType,
                                 item => item.File,
                                 item => item.File.Name,
                                 item => item.File.Author,
                                 item => item.File.ModifiedBy,
                                 item => item.File.ListItemAllFields["Created"],
                                 item => item.File.ListItemAllFields["Modified"],
                                 item => item.File.ListItemAllFields["FileRef"],
                                 item => item.File.Length));

        spClientContext.ExecuteQuery();

        if (listItems != null && listItems.Count > 0)
        {
            foreach (ListItem item in listItems)
            {
                if (item.FileSystemObjectType.Equals(FileSystemObjectType.File))
                {
                    // Do Stuff
                }
            }
        }
    }
}

I tried updating the CAML Query with an order by clause on FieldRef item.File.Name, which did not work. Pretty new to SharePoint / CAML Query so in general not sure how to handle inner objects in the query. Thanks for the help!


Solution

  • Yuo could use FileLeafRef to order by file name,like below:

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