I have a class Order with properties like OrderId
, OrderDate
, Quantity
, and Total. I also have a List<Order>
filled with orders. I want to sort this list by a specific property, such as OrderDate
or OrderId
.
How can I accomplish this in C# using C# list sort methods?
Hey! I’ve done this tons of times
. The simplest way is to use the Sort method with a lambda:
orders.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));
This sorts the list in-place by OrderDate
.
I usually use CompareTo
for date, numeric, or string comparisons, it’s fast and reliable.
If you want descending order, just flip the parameters:
orders.Sort((x, y) => y.OrderDate.CompareTo(x.OrderDate));
Using LINQ’s OrderBy
or OrderByDescending
If you prefer functional style, LINQ works beautifully:
var sortedOrders = orders.OrderBy(o => o.OrderDate).ToList();
OrderBy
creates a new sorted list, leaving the original list untouched.
For descending order, just use OrderByDescending
:
var sortedOrdersDesc = orders.OrderByDescending(o => o.Total).ToList();
I often use this when I want to keep the original list intact for later reference.
Sometimes I need to sort by more than one property, e.g., OrderDate
and then Quantity. I usually do:
var sortedOrders = orders
.OrderBy(o => o.OrderDate)
.ThenBy(o => o.Quantity)
.ToList();
ThenBy
allows secondary sorting rules.
I’ve found this super useful when generating reports or displaying orders in a UI.