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.
Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
Lists (and arrays) of objects that implement Comparable interface can be sorted automatically by Collections.
OrderBy" function utilizes the default comparer for a string. That comparer is not necessarily going to return a sort order based on the ASCII code. For a list of all the different string comparers, see the article on MSDN.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With