List sorting C# using 2 fields

15,255

Solution 1

list.OrderByDescending(o => o.Field2)
    .ThenByDescending(o => o.Field1);

Solution 2

var ordered = objects.OrderByDescending(o => o.SecondDec)
                     .ThenByDescending(o => o.FirstDec);

Then enumerate it or create another collection, e.g. via ToList.

foreach(var obj in ordered)
{
    // ...
}

Solution 3

Other answers show a great way to construct an IEnumerable<T> which, when enumerated, yields the items in your list in the order that you describe. It provides a "view" of the list, so to speak, and does not change the order of the items in the list itself.

If you actually want to sort the list (i.e., change the list in-place such that its items are in order), you can use the List<T>.Sort Method as follows:

list.Sort((x, y) =>
{
    int result = decimal.Compare(y.SecondDecimal, x.SecondDecimal);
    if (result == 0) 
        result = decimal.Compare(x.FirstDecimal, y.FirstDecimal);
    return result;
});

Solution 4

Use OrderByDescending, and ThenBy:

var sorted = items.OrderByDescending(item => item.Decimal2)
    ThenBy(item => item.Decimal1);
Share:
15,255
Vijay V
Author by

Vijay V

Updated on June 30, 2022

Comments

  • Vijay V
    Vijay V almost 2 years

    I have a list of my custom objects. The object contains 1 string and 2 decimals. I would like to sort the list based on the 2nd decimal field descending then the first decimal field.

    For eg:

    object 1 -> "a", 100, 10
    object 2 -> "b", 300, 0
    object 3 -> "c", 200, 200
    object 4 -> "b", 400, 0
    

    would be sorted as object 3, object 1, object 4, object 2

    I apologize if this has already been answered - please point me to that post as I could not find it