Click here to Skip to main content
Click here to Skip to main content

Tagged as

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

, 4 Jan 2011
Rate this:
Please Sign up or sign in to vote.
(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)

Share

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)

 
Hey, I am Pranay Rana, working as a ITA in 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:


Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralI've removed the extra "== null" from the second solution as... PinmemberRichard Deeming4-Jan-11 9:19 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140821.2 | Last Updated 4 Jan 2011
Article Copyright 2010 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid