Problem with CAML SPQuery ItemChildCount result
-
16-10-2019 - |
Question
I know that this query works fine
SPQuery query = new SPQuery();
query.Query = "<OrderBy><FieldRef Name='ItemChildCount' Ascending='FALSE' /></OrderBy>";
But my SPListItemCollection doesn't display what I'm expecting as a result.
Actual Dispaly in C# Actual Display in CAML Query Builder ID | Title | ItemChildCount| ID | Title | ItemChildCount | ---|-------|---------------| ---|-------|----------------| 11 | Abc | 11;#5 | 11 | Abc | 5 | ---|-------|---------------| ---|-------|----------------| 22 | BBB | 22;#9 | 22 | BBB | 9 | ---|-------|---------------| ---|-------|----------------| 24 | Cbc | 24;#7 | 24 | Cbc | 7 |
I wonder why in U2U CAML Query Builder, the sort by ItemChildCount doesn't work. I tried to sort the items by ItemChildCount yet it sorts the ID instead.
But, when I check on the result on C# code immediate window using SPListItem["ItemChildCount"] it displays the concatenated ID and the ItemChildCount resulting to something like this 11;#5.
How will I create a query where I can do some string manipulations on the CAML query. Something like this
Select * from ListCollection Order by ItemChildCount.Replace("11;#","")
If ever this is possible.
Solution
I hate to say it, but I'm afraid I don't think this is possible using CAML. Even joining the list to itself and using a GroupBy
element wouldn't help because GroupBy
isn't equivalent to its SQL counterpart.
My suggestion would be to:
- Query the Item ID and ItemChildCount from the list (unordered)
- Create a dictionary keyed by ItemChildCount (stripped), with the value being an array of item IDs that have that ItemChildCount
- Populate the dictionary with the queried data
- Work through the dictionary's keys in descending order, querying the Items in batches using the In CAML operator
Example of batch query:
<Where><In><FieldRef Name="ID" /><Values><Value Type="Number">1</Value><Value Type="Number">3</Value></Values></In></Where>
P.S. Trying to turn SQL into C# and CAML makes two very disconnected parts of my brain try to work together in a particularly nauseating way. Bleurgh.
OTHER TIPS
try this :
var field = ItemChildCount.Fields.GetFieldByInternalName("ItemChildCount");
var actualCount = field.GetValueAsHtml(ItemChildCount[field.Id]);