Read following post before continuing with this
Problem
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.
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
};Solusion 2
Use 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 ?? "N/A"
};
Summary
Above solution shows how easily we handle null value as well as achieve functionality of the SQL ISNULL function.
No comments:
Post a Comment