How can I sort List based on properties of T?

后端 未结 4 901
误落风尘
误落风尘 2020-12-28 18:21

My Code looks like this :

Collection optionInfoCollection = ....
List optionInfoList = new List

        
4条回答
  •  感动是毒
    2020-12-28 19:18

    If you just want Sort() to work, then you'll need to implement IComparable or IComparable in the class.

    If you don't mind creating a new list, you can use the OrderBy/ToList LINQ extension methods. If you want to sort the existing list with simpler syntax, you can add a few extension methods, enabling:

    list.Sort(item => item.Name);
    

    For example:

    public static void Sort(
        this List source,
        Func selector)
    {
        var comparer = Comparer.Default;
        source.Sort((x, y) => comparer.Compare(selector(x), selector(y)));
    }
    public  static void SortDescending(
        this List source,
        Func selector)
    {
        var comparer = Comparer.Default;
        source.Sort((x, y) => comparer.Compare(selector(y), selector(x)));
    }
    

提交回复
热议问题