chobo2 chobo2 - 1 year ago 113
C# Question

How to use orderby with 2 fields in linq?

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.


Answer Source
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download