177

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наđошƒаӽ
  • 15,289
  • 12
  • 72
  • 86
chobo2
  • 79,578
  • 183
  • 505
  • 811

5 Answers5

336
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
mqp
  • 67,323
  • 14
  • 92
  • 123
78

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
  • 228,647
  • 33
  • 413
  • 517
17

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
  • 11,984
  • 10
  • 61
  • 68
13
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
  • 141
  • 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
  • 3,879
  • 2
  • 32
  • 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