使用Any()时,对象未设置为对象的实例 [英] Object not set to an instance of an object when using Any()

查看:65
本文介绍了使用Any()时,对象未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下LINQ

OfferOrder pricedOfferOrder = OrderData.OfferOrder
  .Where(d => d.Question.Any(e => e.Price != null)).FirstOrDefault().Question);

它工作正常,但是当所有Question中的Price为null时,它将引发以下异常:

It works fine but when Price of all Question are null it throws the following Exception:

对象引用未设置为对象的实例

Object reference not set to an instance of an object

我的课程如下:

public partial class OrderOrderData
{
    public OrderOrderDataOfferOrder[] OfferOrder{get;set}
}

public partial class OrderOrderDataOfferOrder
{
    public OrderOrderDataOfferOrderQuestion[] Question{get;set}
}

public partial class OrderOrderDataOfferOrderQuestion
{
    public OrderOrderDataOfferOrderQuestionPrice Price{get;set;}
}

如何避免这种情况?

推荐答案

如果您正在使用C#6,则可以使用

Provided that you are using C# 6, you could make use of the null conditional operator:

OfferOrder pricedOfferOrder = OrderData.OfferOrder
                                       .Where(d => d.Question?.Any(e => e.Price != null) ?? false)
                                       .FirstOrDefault()?.Question;

问题的根源在d.Question.Any...FirstOrDefault().Question.如果d.Question为null,则调用Any没有任何意义.此外,如果未找到任何元素,则FirstOrDefault返回null.因此,您无法读取null的属性Question.

The problem's root is at the d.Question.Any... and at the FirstOrDefault().Question. If d.Question is null there isn't any meaning on calling Any. Furthermore, FirstOrDefault returns null if no element found. So you can't read property Question of null.

更新

如果使用早期版本的C#(显然可以使用LINQ),则可以尝试以下操作:

If you use a previous version of C# (where LINQ apparently is available) , you could try the following:

OfferOrder pricedOfferOrder = OrderData.OfferOrder
                                       .Where(d => d.Question != null =>
                                                   ? d.Question.Any(e => e.Price != null) 
                                                   : false)
                                       .FirstOrDefault();
var question = pricedOfferOrder !=null ? pricedOfferOrder.Question : null;

这篇关于使用Any()时,对象未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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