Search code examples
c#performancelinqsortingsimultaneous

"How can I efficiently sort a list of custom objects in C# based on multiple properties?


I have a list of custom objects in C#, and I need to sort this list based on multiple properties of the objects. Each object has several properties, and I want to sort the list first by PropertyA in ascending order and then by PropertyB in descending order. What's the most efficient and clean way to achieve this in C#?

Thank you!

I've tried using List.Sort() and OrderBy() with LINQ, but I'm having trouble sorting by multiple properties simultaneously. Can someone provide a code example or point me in the right direction to achieve this sorting efficiently?


Solution

  • With LINQ you can use OrderBy(Descending) followed by ThenBy(Descending).

    Enumerable.ThenByDescending:

    Performs a subsequent ordering of the elements in a sequence in descending order.

    The following:

    var sorted = myCollection
        .OrderBy(i => i.PropertyA)
        .ThenByDescending(i => i.PropertyB)
        .ToList();
    

    Will sort the collection by PropertyA (ascending) then by PropertyB in descending order and put results into a new list.