0

I have the following LINQ

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

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

My classes look like this:

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;}
}

How can I avoid this?

Huma Ali
  • 1,759
  • 7
  • 40
  • 66

2 Answers2

1

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;

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.

Update

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;
Christos
  • 53,228
  • 8
  • 76
  • 108
0

If you are using c#6 Or above

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

For older version

var data = OrderData.OfferOrder
  .Where(d => d.Question.Any(e => e.Price != null)).FirstOrDefault();
OfferOrder pricedOfferOrder = data != null ? data.Question : null;
jitender
  • 10,238
  • 1
  • 18
  • 44