使用Linq检索包含空值的列表
是否可以使用LINQ检索可能包含空值的列表 例如,如果我有这样一个左外连接:使用Linq检索包含空值的列表,linq,list,null,left-join,nullable,Linq,List,Null,Left Join,Nullable,是否可以使用LINQ检索可能包含空值的列表 例如,如果我有这样一个左外连接: var query= from c in db.Customers join o in db.Orders on c.CustomerID equals o.CustomerID into sr from x in sr.DefaultIfEmpty() select x.OrderI
var query= from c in db.Customers
join o in db.Orders
on c.CustomerID equals o.CustomerID into sr
from x in sr.DefaultIfEmpty()
select x.OrderId;
我如何得到一个看起来像{12,13,null,14,null,11,16,17}的列表
这对我不起作用:
query.ToList<decimal?>();
query.ToList();
可能吗?问题是
x。当x
为空时,OrderId
将抛出NullReferenceException
。您需要首先检查null,如果存在对象,则返回属性。比如说
select x == null ? (decimal?)null : x.OrderId;
OrderId
听起来不太像应该是十进制的…问题是x。当x
为空时,OrderId
将抛出NullReferenceException
。您需要首先检查null,如果存在对象,则返回属性。比如说
select x == null ? (decimal?)null : x.OrderId;
OrderId
听起来不太像应该是十进制的…试试:
var query
= from c in db.Customers
join o in db.Orders
on c.CustomerID equals o.CustomerID into sr
select (sr != null : sr.OrderId : null);
变量查询
=来自以db表示的c客户
加入db.Orders中的o
关于c.CustomerID等于o.CustomerID到sr
选择(sr!=null:sr.OrderId:null);
尝试:
变量查询
=来自以db表示的c客户
加入db.Orders中的o
关于c.CustomerID等于o.CustomerID到sr
选择(sr!=null:sr.OrderId:null);
lc是正确的,但直接将select转换为可为null的类型更为简洁
var query= from c in db.Customers
join o in db.Orders
on c.CustomerID equals o.CustomerID into sr
from x in sr.DefaultIfEmpty()
select (decimal?)x.OrderId;
lc是正确的,但直接将select转换为可为null的类型更为简洁
var query= from c in db.Customers
join o in db.Orders
on c.CustomerID equals o.CustomerID into sr
from x in sr.DefaultIfEmpty()
select (decimal?)x.OrderId;
谢谢大家!!这让我困惑了一段时间。谢谢你的回答,谢谢!这让我困惑了一段时间。感谢你的回答。你没有解释你想要那些
null
s对应什么。没有订单的客户?您没有解释您希望这些null
s对应什么。没有订单的客户?选择应该是select(sr!=null?sr.OrderId:null);select应该是select(sr!=null?sr.OrderId:null);