-1

I have a list like the following one:

|Name|Val. Date 1| Val. Date 2|
|PA  |        200|         200|
|PB  |          0|         300|
|PC  |        200|           0|
|PD  |        150|         150|

Ordering the list by Val. Date1 will give me something like: PA, PC, PD and PB. and something similar if I do it for Val. Date 2.

But what I really need to do, is to order it by the highest value recorded in Date 1 or Date 2, what results in something like this: PB, PA, PC and PD.

How can I solve this matter?

cap7
  • 482
  • 5
  • 24

3 Answers3

3

use Math.Max() to get the maximum value and then order by it:

 list.OrderByDescending(x => Math.Max(x.Date1, x.Date2));
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
  • if you add a `ThenByDescending` with the sum of both values it should work in the border-cases ;9 – Random Dev Mar 30 '15 at 11:29
  • 1
    @CarstenKönig: It cannot be deduced from the question that this is the desired behavior. OP asks for ordering by the highest value of two properties, and this solution provides that. – David Hedlund Mar 30 '15 at 11:31
  • 2
    OP wants the lists to be order by having using the heighest of the 2 numbers of the same index number so it uses the `300` and not the `0` by `PC`. It should compare the 2 numbers with the same index number and see what one the highest is, and then order the lists with only using the highest numbers – maam27 Mar 30 '15 at 11:33
  • 1
    The provided answer works as I wanted. I knew there was a away to do it with linq but I didn't remember to use the Math class :) – cap7 Mar 30 '15 at 11:37
2

Since you are using a list, you can do an inline sort of the list using List.Sort(Comparison<T>):

list.Sort((lhs, rhs) => 
(
    Math.Max(lhs.Val.Date1, lhs.Val.Date2) - 
    Math.Max(rhs.Val.Date1, rhs.Val.Date2)
));

If you are assigning the results of the Linq solution back to a list using .ToList(), then doing an in-place sort instead will be much more efficient with one important caveat:

List.Sort() is NOT a stable sort, so that it doesn't preserve the ordering of equal values. The Linq OrderBy, however, is a stable sort.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

Another way is to use something like:

var sortedList = ListOfData.OrderByDescending(x=>x.Val1).ThenByDescending(x=>x.Val2);

See:
Multiple “order by” in LINQ
Ordering data in LINQ queries by more than one column
Multiple Field Sorting by Field Names Using Linq

Community
  • 1
  • 1
Maciej Los
  • 8,468
  • 1
  • 20
  • 35