Reputation: 7967
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.
Upvotes: 30
Views: 30149
Reputation: 110221
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?
Upvotes: 72
Reputation: 9864
The easiest way in my opinion is to use linq :
itemsList = itemsList.OrderByDescending(ob => ob.status ).ThenBy(ob => ob.date).ToList();
Upvotes: 2
Reputation: 19872
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
Upvotes: 2
Reputation: 52808
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);
}
Upvotes: 2
Reputation: 82375
Shouldn't be too difficult, just make T
implement IComparable
using your comparison rules and you should be set.
Upvotes: 17