65.9K
CodeProject is changing. Read more.
Home

(Linq and Nullable Values) OR (SQL ISNULL with LINQ)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Dec 24, 2010

CPOL
viewsIcon

56343

(Linq and Nullable Values) OR (SQL ISNULL with LINQ)

Here in this small post, I am just going to show how you can deal with the Nullable values in LINQ queries and how you can achieve functionality like SQL ISNULL function. Read the following post before continuing with this: Problem I am dealing with the LINQ queries I have to diplay "N/A" where the value is null for the given property/column. Solution 1
Use of ternary operator as in the below example and the 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 {
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 operator (??) as in the below example and and 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 {
u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
UserId = m.UserId,
MobileNo = m.MobileNo ?? "N/A" 
};
Summary The above solution shows how easily we handle null value as well as achieve functionality of the SQL ISNULL function.