views:

39

answers:

2

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

+5  A: 

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.

Alternatively:

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.

Jon Skeet
+1  A: 

try this:

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