Custom OrderBy on a List<T>
I'm trying to figur开发者_如何学JAVAe 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.
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?
Shouldn't be too difficult, just make T
implement IComparable
using your comparison rules and you should be set.
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);
}
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
The easiest way in my opinion is to use linq :
itemsList = itemsList.OrderByDescending(ob => ob.status ).ThenBy(ob => ob.date).ToList();
精彩评论