Search code examples
c#linqsortingsharepointcaml

Sorting using C# , LINQ


I have a list of items in a SharePoint which has Title, Date and Priority. I would like to sort this collection on my client application while displaying it ,sorting need to first by Date Descending and then within a set of objects for a date, it should sort objects by Priority.

I am using below LINQ code, which is not providing the expected result. Means the below code not sorting object by priority with in a date.

 var results = spObjects.OrderByDescending(n => n.Date).ThenBy(t => t.Priority);

Unsorted collection is as below

enter image description here

Sorted Collection - Expectation

enter image description here

I am using SharePoint CAML query, since I am fetching these object from SP and I found it difficult to do it in CAML, but I assume this can be done using LINQ on C# side, Isnt it ? Could anyone please help ?


Solution

  • I'll bet you that n.Date is a DateTime object, with hours, minutes, and seconds. Your Linq looks good, so you probably have different times that are causing items later in the day with lower priorities to be sorted before items earlier in the day.

    Try something like:

     var results = spObjects.OrderByDescending(n => new DateTime(n.Date.Year, n.Date.Month, n.Date.Day)).ThenBy(t => t.Priority);