LINQ and Nullable Values or SQL ISNULL with LINQ

By | March 1, 2011

In this tips I am going to show how you can deal with the Nullable values in LINQ queries and how you can achieve functionality like SQL ISNULL function.

Let’s put it as a problem statement

I am dealing with the LINQ queries, In which I have to diplay “N/A” were the value is null for the given property/column.

Now you can have multiple solution to do that

Solution 1

You can use ternary operator as shwon in below example. Here MobileNo = "N/A" for the null values

var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
 Id=u.Id,
 FirstName=u.FirstName,
 LastName=u.LastName,
 UserId=m.UserId,
 MobileNo = (m.MobileNo == null) ? "N/A" : m.MobileNo
};

Solution 2

Use special Coalescing operator (??) as showin in below example. Here MobileNo = "N/A" for the null values

var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
 Id=u.Id,
 FirstName=u.FirstName,
 LastName=u.LastName,
 UserId=m.UserId,
 MobileNo = m.MobileNo == null ?? "N/A"
};

Above solution shows how easily we handle null value as well as achieve functionality of the SQL ISNULL function.
Shared By : Pranay Rana
Source : http://pranayamr.blogspot.com/2010/12/linq-and-nullable-values-or-sql-isnull.html