如何忽略Linq中的空值? [英] How Do I Ignore Null Values In Linq?

查看:115
本文介绍了如何忽略Linq中的空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用linq查询获取名字和姓氏为姓名,但如果姓氏列中的任何值为null,则只需在该字段取名字,我该如何解决?

i已写像这样

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

var info=(from r in spe.contacts select new 
{
fullname=r.firstname+" "+r.lastname
});
return info;



它运行正常,但是当姓氏值为null时也没有显示第一个名字,请帮我解决这个问题????


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????

推荐答案

不确定你想要做什么。



1.如果你想显示名字,即使姓氏为空

Not sure exactly what you want to do.

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



(你可以为名字做同样的事。



2.如果你想忽略空名称


(You can do the same for first name.

2. If you want to ignore null names

var info = (from r in spe.contacts select new
{
    if ((r.firstname != null) && (r.lastname != null))
        fullname = r.firstname + " " + r.lastname;
});
return info;


试试这个



Try this

var info=(from r in spe.contacts select new 
{
fullname = (r.fristname== DBNull.Value ? "":r.fristname)+" "+(r.lastname== DBNull.Value ? "":r.lastname);
});
return info;


您可以使用三元运算符。

试试这个:



you can use ternary operators for this.
try this:

var info=(from r in spe.contacts select new
{
fullname=r.firstname+" "+ (r.lastname != null) ? r.lastname : "";
});
return info;


这篇关于如何忽略Linq中的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆