views:

155

answers:

1

I am trying to sort a LINQ to SQL query based on two fields. The first field is occasionally null which automatically sorts to the top of an ascending query. Is there any way to make the null entries sort to the bottom?

Here is an example:

From x in SampleDataContext.Event _
Order By x.Date, x.Sequence_Number _
Select x.Date, x.Sequence_Number

Would return:

  • NULL, 1
  • NULL, 4
  • 12/2/09, 5
  • 12/3/09, 2
  • 12/3/09, 3

Desired order:

  • 12/2/09, 5
  • 12/3/09, 2
  • 12/3/09, 3
  • NULL, 1
  • NULL, 4
+7  A: 

If they're strings:

Order By (string.IsNullOrEmpty(x.Date) ? "zzzzzz" : x.Date)

If they're nullable datetimes:

Order By (x.Date ?? DateTime.MaxValue)
David Hedlund
nice, didnt know you could do that
Allen