0

I can't seem to return a set of items in the order I want while using a CAML query.

I want to grab the newest item in a specific folder, so I want to query the folder, order it by ID (though I'm leaning toward using the Modified date in case versioning is on and the ID doesn't change) in descending order. I've tried sorting by ID, Created, and Modified to no avail.

Here is the working query/code which assumes last item is always the highest ID and that the highest ID represents the most recently added document.

            List list = ctx.Web.Lists.GetByTitle("Some Docs");
            CamlQuery query = new CamlQuery();
            query.ViewXml = @"<View><ViewFields></ViewFields></View>"; //intentionally empty to reduce returned field count from 57 to 17
            query.FolderServerRelativeUrl = "/Some%20Docs/TestFolder";

            ListItemCollection items = list.GetItems(query);
            ctx.Load(items);
            ctx.ExecuteQuery();

            ListItem excelItem = items.Last();

I'd like to clean it up a bit or at least understand what I'm doing wrong here for future reference:

    List list = ctx.Web.Lists.GetByTitle("Some Docs");
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = @"<View>
    <ViewFields>
      </ViewFields>
      <OrderBy>
    <FieldRef Name='ID' Ascending='FALSE'/>
  </OrderBy>
    </View>";
                    query.FolderServerRelativeUrl = "/Some%20Docs/TestFolder";

                    ListItemCollection items = list.GetItems(query);
                ctx.Load(items);
                ctx.ExecuteQuery();
ListItem excelItem = list.GetItems(query)[0]; //this is returning the first item (lowest ID) instead

Note: Adding "Scope='RecursiveAll'" didn't help, but I'd assume that might be a conflict with the url I'm passing in. I also tried "Override='TRUE'.

0

Please try below mentioned code. It will work.

query.ViewXml = @"<View>
      <Query>
      <OrderBy>
         <FieldRef Name='ID' Ascending='FALSE'/>
      </OrderBy>
      </Query>
      <ViewFields>
      </ViewFields>
    </View>";
  • The items are still returned in ascending order. – Dinerdo Jul 19 '15 at 0:16
  • 1
    Well, Sorry but your OrderBy tags need to be contained within a Query tag. Please check the answer which i have edited recently. – Hardik Jul 20 '15 at 5:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.