LINQ and Nullable Values or SQL ISNULL with LINQ - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Saturday, May 28, 2011

LINQ and Nullable Values or SQL ISNULL with LINQ

In this tips I am going to show how you can deal with the Nullable values in LINQ queries and how you can achieve functionality like SQL ISNULL function.

Let's put it as a problem statement

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.

Now you can have multiple solution to do that

Solution 1

You can use ternary operator as shwon in below example. HereMobileNo = "N/A" for the null values
[sourcecode language="csharp"]
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
};
[/sourcecode]

Solution 2

Use special Coalescing operator (??) as showin in below example. Here MobileNo = "N/A" for the null values
[sourcecode language="csharp"]
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"
};
[/sourcecode]

Above solution shows how easily we handle null value as well as achieve functionality of the SQL ISNULL function.
Source : http://pranayamr.blogspot.com/2010/12/linq-and-nullable-values-or-sql-isnull.html

No comments:

Post a Comment