LINQ and Nullable Values or SQL ISNULL with LINQ

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

Pranay Rana

Pranay is MVB on DZone and working as a Senior Software engineer. Doing Web development using Asp.Net ,C#, MS sql server, JQuery/Javascript that he had experience of 4.3 years now. For himdef. of programming is : Programming is something that you do once and that get used by multiple for many years You can visit him on his blog - http://pranayamr.blogspot.com/ Follow on twitter : @pranayamr