views:

1207

answers:

1

I have started using Linq to SQL for a project im working on and i have run into a problem when ordering by a DateTime field but since the DateTime allows nulls the nulls are coming up as less than the actual dates in there.

So i pretty much want the ones with a date to be at the top (ordered either way) then all the ones with no date set.

jobList = from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          select ju.Job;
return jobList.OrderByDescending(j => j.EndDate);
+12  A: 

This is a bit of a hack, but it appears to work with Linq to SQL:

return from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          orderby ju.Created ?? DateTime.MaxValue descending;

So I'm substituting the maximum possible DateTime value when the actual "Create" value is null. That'll put all the null values at the top.

Another approach is to order by whether the date field has a value. This works too:

return from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          orderby ju.Created.HasValue descending
          orderby ju.Created descending;
Matt Hamilton
I'm can't put my finger on why exactly, but I find your second solution quite beautiful
David Hall
Looking at the question again, it's a bit ambiguous as to whether the asker wants the null values first or not (he says he doesn't, but then orders the query descending). Either way it's a small step from either of these code snippets to what he wants.
Matt Hamilton
Thanks matt thats exactly what i was looking for. and as for the ordering this was just an example, i have to order it other ways in different places but the null values are always last.
d1k_is