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.
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);
}
Shouldn't be too difficult, just make T
implement IComparable using your comparison rules and you should be set.
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
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?
The easiest way in my opinion is to use linq :
itemsList = itemsList.OrderByDescending(ob => ob.status ).ThenBy(ob => ob.date).ToList();