How to Sort a List by a property in the object

前端 未结 20 1988
醉梦人生
醉梦人生 2020-11-21 08:25

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a l

20条回答
  •  长情又很酷
    2020-11-21 08:47

    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)));
    }
    

提交回复
热议问题