How to use orderby with 2 fields in linq?
C#LinqC# Problem Overview
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.
C# Solutions
Solution 1 - C#
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
Solution 2 - C#
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
.
Solution 3 - C#
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"
Solution 4 - C#
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);
Solution 5 - C#
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