Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
i want to take first name and last as fullname using linq query, but if any value is null in last name column just take firstname at that field,how can i solve this?
i have written like this
C#
var info=(from r in spe.contacts select new 
{
fullname=r.firstname+" "+r.lastname
});
return info;

it is working fine, but when ever last name value is null it is not displaying even firstname also , please help me how to solve this????
Posted
Updated 13-Sep-14 2:52am
v2

Not sure exactly what you want to do.

1. If you want display the first name even if last name is null
C#
var info = (from r in spe.contacts select new
{
    fullname = r.firstname + " " + (r.lastname != null) ? r.lastname : "";
});
return info;

(You can do the same for first name.

2. If you want to ignore null names
C#
var info = (from r in spe.contacts select new
{
    if ((r.firstname != null) && (r.lastname != null))
        fullname = r.firstname + " " + r.lastname;
});
return info;
 
Share this answer
 
Comments
pavan_ kumar 15-Sep-14 10:19am    
ya, it is working good, thanks
Try this

C#
var info=(from r in spe.contacts select new 
{
fullname = (r.fristname== DBNull.Value ? "":r.fristname)+" "+(r.lastname== DBNull.Value ? "":r.lastname);
});
return info;
 
Share this answer
 
v3
Comments
pavan_ kumar 15-Sep-14 10:20am    
it is not working, it is showing the error "cannot implicitly convert dbnull to bool"
you can use ternary operators for this.
try this:

C#
var info=(from r in spe.contacts select new
{
fullname=r.firstname+" "+ (r.lastname != null) ? r.lastname : "";
});
return info;
 
Share this answer
 
Comments
pavan_ kumar 15-Sep-14 10:21am    
working fine,thanks
Use the Null coalescing operator[^]:
C#
var info=(from r in spe.contacts select new
{
fullname=(r.firstname?? string.Empty) + " " + (r.lastname ?? string.Empty)
});
return info;
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900