Does anyone know how to return an ordered list of strings with null values last? I have something like this:
using(var context = new DomainEntities()) { var result = context.Users.OrderBy(u => u.LastName).ThenBy(u => u.FirstName); }
My problem though is that this query returns null values before non-null values.
Any thoughts?
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.
SQL ORDER BY Clause Handling NULLS This means that if you specify a column in the ORDER BY clause that has null values in ascending order the NULL values will appear first in the result set. Conversely, if you specify descending order, they will appear last in the result set.
Some columns cannot have a meaningful value in every row. Db2 uses a special value indicator, the null value , to stand for an unknown or missing value. A null value is a special value that Db2 interprets to mean that no data is present. If you do not specify otherwise,Db2 allows any column to contain null values.
I would do:
using(var context = new DomainEntities()) { var result = context.Users.OrderBy(u => u.LastName == null) .ThenBy(u => u.LastName) .ThenBy(u => u.FirstName == null) .ThenBy(u => u.FirstName); }
...which should produce reasonable SQL.
EDIT: explanation (taken from Craig's comment):
Because false
sorts before true
.
var result = context.Users.OrderBy(x => x.FirstName ?? x.LastName);
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