C# 在 Lambda 表达式中检查 Null 的干净方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15327752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clean way to check for Null in Lambda Expressions
提问by user1527762
I have seen a lot of questions on this but was not able to find a clean solution:
我已经看到了很多关于此的问题,但无法找到一个干净的解决方案:
I have the following lambda expression:
我有以下 lambda 表达式:
var result = Store.FirstOrDefault(x.Products.Coupon[0] == 100);
I would like to check for null for the Coupon collection to check to see if its not null and then compare the first coupon with the value 100. What would be a clean way to check for NULL for Coupon in the lambda? I do not want to use an extension method to check for null. I would like to do the check inline.
我想检查 Coupon 集合的 null 以检查它是否不为 null,然后将第一个优惠券与值 100 进行比较。在 lambda 中检查 Coupon 的 NULL 的干净方法是什么?我不想使用扩展方法来检查 null。我想做内联检查。
采纳答案by Corey Sunwold
var result = Store.FirstOrDefault(x => x.Products.Coupon != null && x.Products.Coupon.Any() && x.Products.Coupon[0] == 100);