5

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

Vijay V
  • 389
  • 5
  • 11
  • 23
  • 1
    you should include the `Properties names` of your `object`, that would be better. Otherwise I guess the answerers will `suppose you have ...` or even don't suppose anything. – King King Aug 23 '13 at 22:21
  • 1
    This was already answered [here](http://stackoverflow.com/questions/298725/multiple-order-by-in-linq) and [here](http://stackoverflow.com/questions/289010/c-sharp-list-sort-by-x-then-y?rq=1). – Yuriy Rypka Aug 23 '13 at 22:34

4 Answers4

11
list.OrderByDescending(o => o.Field2)
    .ThenByDescending(o => o.Field1);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
6

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;
});
dtb
  • 213,145
  • 36
  • 401
  • 431
5
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)
{
    // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Use OrderByDescending, and ThenBy:

var sorted = items.OrderByDescending(item => item.Decimal2)
    ThenBy(item => item.Decimal1);
McGarnagle
  • 101,349
  • 31
  • 229
  • 260