How to sort Generic List Asc or Desc?

后端 未结 2 418
情话喂你
情话喂你 2021-02-01 19:09

I have a generic collection of type MyImageClass, and MyImageClass has an boolean property \"IsProfile\". I want to sort this generic list which IsProfile == true stands at the

2条回答
  •  旧巷少年郎
    2021-02-01 19:46

    You can use .OrderByDescending(...) - but note that with the LINQ methods you are creating a new ordered list, not ordering the existing list.

    If you have a List and want to re-order the existing list, then you can use Sort() - and you can make it easier by adding a few extension methods:

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

    Then you can use list.Sort(x=>x.SomeProperty) and list.SortDescending(x=>x.SomeProperty).

提交回复
热议问题