I have a class called Order
which has properties such as OrderId
, OrderDate
, Quantity
, and Total
. I have a l
Here is a generic LINQ extension method that does not create an extra copy of the list:
public static void Sort(this List list, Func expression)
where U : IComparable
{
list.Sort((x, y) => expression.Invoke(x).CompareTo(expression.Invoke(y)));
}
To use it:
myList.Sort(x=> x.myProperty);
I recently built this additional one which accepts an ICompare
, so that you can customize the comparison. This came in handy when I needed to do a Natural string sort:
public static void Sort(this List list, Func expression, IComparer comparer)
where U : IComparable
{
list.Sort((x, y) => comparer.Compare(expression.Invoke(x), expression.Invoke(y)));
}