且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何忽略Linq中的空值?

更新时间:2021-09-28 01:40:38

不确定你想要做什么。



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;