IntroductionHere in this tip I am going to show you, how you can deal with the Nullable values in LINQ queries and how you can achieve functionality like SQL ISNULL function. Read following post before continuing with this ProblemI am dealing with the LINQ queries, In which I have to diplay "N/A" were the value is null for the given property/column. Solution 1You 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
};
Solusion 2Use special Coalescing operator 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"
};
ConclusionAbove solution shows how easily we handle null value as well as achieve functionality of the SQL ISNULL function. |