188

Say I have these values in a database table

id = 1
StartDate = 1/3/2010
EndDate =  1/3/2010

id = 2
StartDate = 1/3/2010
EndDate = 1/9/2010

Now I have so far this orderby for my linq

var hold = MyList.OrderBy(x => x.StartDate).ToList();

I want to order it however also using the end date.

Like so the order I would want this in as

id 2
id 1

So endDates that are greater go first. I am not sure if I need to change this to use some compare function or something.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
chobo2
  • 83,322
  • 195
  • 530
  • 832

5 Answers5

364
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
mqp
  • 70,359
  • 14
  • 95
  • 123
81

Use ThenByDescending:

var hold = MyList.OrderBy(x => x.StartDate)
                 .ThenByDescending(x => x.EndDate)
                 .ToList();

You can also use query syntax and say:

var hold = (from x in MyList
           orderby x.StartDate, x.EndDate descending
           select x).ToList();

ThenByDescending is an extension method on IOrderedEnumerable which is what is returned by OrderBy. See also the related method ThenBy.

jason
  • 236,483
  • 35
  • 423
  • 525
24

If you have two or more field to order try this:

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);

You can add other fields with clasole "ThenBy"

daniele3004
  • 13,072
  • 12
  • 67
  • 75
14
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

Note that you can use as well the Descending keyword in the OrderBy (in case you need). So another possible answer is:

MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);
Hugo Passos
  • 151
  • 1
  • 3
6

VB.NET

 MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)

OR

  From l In MyList Order By l.StartDate Ascending, l.EndDate Descending
Abdul Saboor
  • 4,079
  • 2
  • 33
  • 25
  • 2
    Is there any difference between `From l In MyList Order By l.StartDate Ascending Order By l.EndDate Descending` and `From l In MyList Order By l.StartDate Ascending, l.EndDate Descending`? – Oleksandr Oct 07 '14 at 12:10
  • @Oleksandr Yes, Abdul's variant is equivalent to merely doing the second order, so it's not correct. – John Nov 05 '14 at 13:52
  • @John and @ oleksandr Thanks for identifying the mistake not it has been corrected – Abdul Saboor Mar 09 '15 at 16:08