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

62 Views Asked by At

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?

3

There are 3 best solutions below

0
Guru Stron On BEST ANSWER

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.

0
Antonio Marcos Becker On

You can use ThenBy after OrderBy. And don't forget to use .ToList() in the end.

var sortedList = listOfCustomObjects
.OrderBy(obj => obj.PropertyA)
.ThenBy(obj => obj.PropertyB)
.ToList();
0
TJR On

I would make your custom object implement IComparable<MyCustomObject> and then you could build your comparison logic directly into the object so that it sorts by PropertyA ascending and by PropertyB descending.

public int CompareTo(MyCustomObject other)
{
    // depending on if you want nulls at the beginning or end
    // you may want this to be 1 or -1 or you may want to throw if you aren't
    // allowing null
    if (other == null)
        return 1;

    var result = PropertyA.CompareTo(other.PropertyA);

    // the PropertyA values are not the same, so the sorting is determined
    // by PropertyA only
    if (result != 0)
        return result;

    // the PropertyA values are the same, so now sort by PropertyB descending.
    result = other.PropertyB.CompareTo(PropertyB);

    return result;
}

With that logic built in, then you can just do MyList.Sort() and it will sort based on your IComparable<MyCustomObject>

This should be more efficient than Linq solutions since the comparisons will be done in a single shot, but this may be kind of a weird solution if the sorting of this custom object isn't always going to be done as described in your CompareTo implementation, so if this is a unique one off sorting it may make more sense to use a Linq solution.