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:
  1. SELECT value  
  2. FROM foo  
  3. 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:
  1. foo.OrderBy(i => i.x == null ? 1 : 0)  
  2.    .ThenBy(i => i.x);