order collection by date where some items dont have a value

i have a collection of objects and i am looking to sort by a property that is a DateTime?

  list.OrderBy(r => r.Milestone)

where milestone is a:

  public DateTime? Milestone { get; set; }

it seems to put all of the items with novalue at the top of the sort. Is there anyway to sort by date but put the empty items at the bottom of the list. (i dont care about the ordering of the empty ones of course)

So if i have 4 items:

  1. 1/1/2001
  2. 1/1/2002
  3. [No DateTime]
  4. 1/1/2004

i would want to order the list 1,2,4,3


One easy option:

list.OrderBy(r => r.Milestone ?? DateTime.MaxValue)

That won't work nicely if there are values with a mileston of DateTime.MaxValue, of course.

Recently there was a related question about implementing IComparer<T> to put nulls at the end, but I can't find it now... the above is definitely the simplest solution though, if you won't be using MaxValue for anything else.


list.OrderBy(r => !r.Milestone.HasValue)
    .ThenBy(r => r.Milestone)

will order all the values that do have a milestone first, and then the ones which don't. That way you it will work even if some milestones use DateTime.MaxValue. It's a little more obscure to my eyes, but you may prefer it.

try this:

list.OrderBy(r => r.Milestone.GetValueOrDefault(DateTime.Maxvalue)) 

Need Your Help

Gremlin graph traversal backtracking

graph orientdb traversal backtracking gremlin

I have some code that generates gremlin traversals dynamically based on a query graph that a user supplies. It generates gremlin that relies heavily on backtracking. I've found some edge cases th...

Java - connecting to a SQL Server database on Linux

java sql-server linux jdbc freetds

I've downloaded and imported into my project this JDBC driver that supposedly supports Linux (albeit tested only on SUSE Linux).