How to do double orderby in CAML Query?

omega picture omega · Nov 17, 2012 · Viewed 14.9k times · Source

I am using camel query in visual studio c# to get items from a list from sharepoint 2010. The list items has two fields that I want to use in the caml query. One is "Section" and the other is "Order By". The query needs to order the items in a certain way. First it needs to sort it by Section (ascending=true), and then for each a secondary sorting by Order By (ascending = true).

For example the result would be like this:

<item> <Section> <Order By>
item1  A 1
item2  A 3
item3  B 1
item4  B 2
item5  C 5
item6  C 6

So far I have this:

        SPQuery query = new SPQuery();
        query.Query = "<Query><OrderBy><FieldRef Name='" + Root_List.Fields.GetField(SECTION_COLUMN).InternalName + "' Ascending='True'/></OrderBy></Query>";
        item_collection = Root_List.GetItems(query);

But how do I apply the secondary orderby?

Note: Section is a string field and order by is a number field.

Answer

Steve Mannina picture Steve Mannina · Nov 18, 2012

Per this page on MSDN, you can include more than one FieldRef inside the OrderBy element:

http://msdn.microsoft.com/en-us/library/ms467378.aspx

The example given is:

<OrderBy>
  <FieldRef Name="Newcomers"/>
  <FieldRef Name="Years" Ascending="FALSE"/>
  <FieldRef Name="Location"/>
</OrderBy>