Click here to Skip to main content
15,860,861 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
4 Jan 2011CPOL 55.5K   6   2
(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)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
QuestionNot a generic LINQ answer Pin
JVMFX4-May-20 7:40
JVMFX4-May-20 7:40 
GeneralI've removed the extra "== null" from the second solution as... Pin
Richard Deeming4-Jan-11 9:19
mveRichard Deeming4-Jan-11 9:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.