Custom OrderBy on a List<T>

ぃ、小莉子 提交于 2020-08-22 08:09:30

问题


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...

"Urgent": I want these at the top of the list, no particular order
date = null
status = "Urgent"

"Normal": I want these ordered by date after the Urgent cases
date = any valid date/time
status = "On Time"

"Later": I want these at the bottom of the list, no particular order
date = null
status = "Later"

Any thoughts? Should I use an IQuerable object instead of List? I can always .ToList() the object later to send to my view.


回答1:


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




回答2:


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?




回答3:


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



回答4:


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




回答5:


The easiest way in my opinion is to use linq :

itemsList = itemsList.OrderByDescending(ob => ob.status ).ThenBy(ob => ob.date).ToList();


来源:https://stackoverflow.com/questions/5278241/custom-orderby-on-a-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!