Thursday, January 21, 2010

Sorting NULL LAST in LINQ-to-SQL

There might be some time that you need to put NULL value into last when sorting a result set. In SQL Server, you can do something like this:

SELECT value
FROM foo
ORDER BY (CASE WHEN x IS NULL THEN 1 ELSE 0 END), x

You might want to ask the mapping of LINQ-to-SQL. Here you go:

foo.OrderBy(i => i.x == null ? 1 : 0)
.ThenBy(i => i.x);