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);
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 !=
In SQL Server just insert NULL in the Datetime column: INSERT INTO Table(name, datetimeColumn, ...) VALUES('foo bar', NULL, ..);
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With