LINQ and Nullable Values or SQL ISNULL with LINQ

Posted By  pranay rana On 12 Jan 2011 21:01:57
emailbookmarkadd commentsprint
No of Views:829
Bookmarked:0 times
Votes:0 times

Introduction

Here 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

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 == null ?? "N/A"
};

Conclusion

Above solution shows how easily we handle null value as well as achieve functionality of the SQL ISNULL function.

Sign Up to vote for this article
Other popular Tips/Tricks
    In this tip I am going to discuss about how to get the difference between two table/ entity sets For Ex
    Published Date : 04/Apr/2011
    In my current project I am using Linq To Sql ORM as my database layer for doing database operation. Now as I am moving further I got requirement to that I have to filter one table record form another table.
    Published Date : 05/Mar/2011
    Linq operator provides great flexibility and easy way of coding. Let’s again take one more example of distinct operator. As name suggest it will find the distinct elements from IEnumerable
    Published Date : 10/Jan/2011
    I am using Linq-To-Object in my current project to remove some extra loops and I have found one of the great keyword in Linq called ‘Let’
    Published Date : 26/Aug/2010
    Linq is almost providing all the functionalities and i have found one another great operator called range operator which will return a sequence of integer number from start point to number of count
    Published Date : 01/Jul/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top