Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom OrderBy on a List<T>

Tags:

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.

like image 392
BZink Avatar asked Mar 11 '11 20:03

BZink


People also ask

How to sort items in a list C#?

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.

Does list auto sort?

Lists (and arrays) of objects that implement Comparable interface can be sorted automatically by Collections.

Does OrderBy work on string?

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.


2 Answers

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?

like image 87
Amy B Avatar answered Oct 03 '22 22:10

Amy B


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

like image 40
Quintin Robinson Avatar answered Oct 03 '22 23:10

Quintin Robinson