Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

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

4.50/5 (2 votes)
4 Jan 2011CPOL 56.3K  
(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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)