Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering nullable DateTime in Linq to SQL

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); 
like image 420
dkarzon Avatar asked Jul 10 '09 04:07

dkarzon


People also ask

How do you handle null values in LINQ query?

An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query. var query1 = from c in categories where c !=

How do I pass DateTime null in SQL?

In SQL Server just insert NULL in the Datetime column: INSERT INTO Table(name, datetimeColumn, ...) VALUES('foo bar', NULL, ..);

Can DateTime be nullable?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

How do you make a date time nullable?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.


1 Answers

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; 
like image 200
Matt Hamilton Avatar answered Sep 22 '22 03:09

Matt Hamilton