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);

1 comment:

Tahir Hassan said...

In actual fact, you can use

foo.OrderBy(i => i.x == null)
.ThenBy(i => i.x);

which shaves a few characters off.

I have written a useful extension method that you can use as follows:

foo.OrderBy(i => i.x)
.NullsLast(i => i.x);

alternatively you can easily define a extension method that combines the two actions and produces

foo.OrderByNullsLast(i => i.x);

You can find the source code at:

http://tahirhassan.blogspot.com/2010/06/linq-to-sql-order-by-nulls-last.html

Thanks for the inspiration.