Custom OrderBy on a List

前端 未结 5 1156
旧巷少年郎
旧巷少年郎 2021-02-18 18:51

I\'m trying to figure out the best way to custom sort a List. Lets say that T is a Object with a date(DateTime?) property and a status(string) property.

I have 3 cases.

相关标签:
5条回答
  • 2021-02-18 19:18

    You could just use an extension method:

    Something like this...

    public static IOrderedEmumerable<MyType> OrderForDisplay (this IEnumerable<MyType> input)
    {
      return
        input
        .OrderBy(item => item.Status)
        .ThenByDescending(item => item.Status == 1 ? DateTime.MaxDate : item.date);
    }
    
    0 讨论(0)
  • 2021-02-18 19:22

    Shouldn't be too difficult, just make T implement IComparable using your comparison rules and you should be set.

    0 讨论(0)
  • 2021-02-18 19:27

    You will need to provide an implementation of IComparer, and then you can pass it in using the following overload:

    public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IComparer<TKey> comparer
    )
    

    See: http://msdn.microsoft.com/en-us/library/bb549422.aspx

    0 讨论(0)
  • 2021-02-18 19:31
    query = query.OrderBy(x =>
      x.Status == "Urgent" ? 1:
      x.Status == "Normal" ? 2:
      3)
      .ThenBy(x => 
      x.Status == "Urgent" ? null:
      x.Status == "Normal" ? x.Date:
      null);
    

    Random musing: Does Ordering belong to the query, or to the class?

    0 讨论(0)
  • 2021-02-18 19:32

    The easiest way in my opinion is to use linq :

    itemsList = itemsList.OrderByDescending(ob => ob.status ).ThenBy(ob => ob.date).ToList();
    
    0 讨论(0)
提交回复
热议问题