我收到以下LINQ查询的空异常
List<Subscription> product_subscriptions = (from i in _subscriptions
where i.SubscriptionLines.Any(l =>
l.ProductNo == isbn)
select i).ToList();在某些情况下,SubscriptionLines可以为空,来自子列表的ProductNo也可以为空。我们是否可以在相同的查询中避免这种空异常
发布于 2020-10-22 19:16:58
from x in y where z语法,因为它会使查询更难阅读。所有很酷的孩子现在都在专门使用扩展方法。SQL
NULL“(全部大写)应该只在讨论C或时使用。在C#中,它是"null“(在C++中,每个人都应该使用nullptr而不是NULL宏,但这是另一回事)。List product_subscriptions = _subscriptions .Where( s => s.SubscriptionLines.Any( line => line.ProductNo == isbn )) .ToList();
.Where()步骤:List product_subscriptions = _subscriptions .Where( s => s.SubscriptionLines != null ) .Where( s => s.SubscriptionLines.Any( line => line.ProductNo == isbn )) .ToList();
- Note that it doesn't matter if `line.ProductNo` can be null because the `==` operator handles `null` values fine. If `line` itself can be null, then you can workaround that by changing the `Any` predicate to this: `line => line?.ProductNo == isbn`.发布于 2020-10-22 19:28:14
访问前检查SubscriptionLines is是否为null`。例如:
var query=from s in _subscriptions
where s.SubscritpionLines !=null
&& s.SubscriptionLines.Any( line => line.ProductNo == isbn )
select s;
var product_subscriptions=query.ToList();您还可以使用null-safe运算符:
var query=from s in _subscriptions
where s.SubscritpionLines
?.Any( line => line.ProductNo == isbn ) ==true
select s;最终会变得更丑陋。使用流畅的语法:
var product_subscriptions = _subscriptions
.Where(s=>s.SubscritpionLines !=null
&& s.SubscriptionLines.Any(
line => line.ProductNo == isbn ))
.ToList();哪个更丑陋,还是:
var product_subscriptions = _subscriptions
.Where(s=>s.SubscritpionLines
?.Any( line => line.ProductNo == isbn ) ==true)
.ToList();https://stackoverflow.com/questions/64481012
复制相似问题