SamJolly
SamJolly

Reputation: 6487

How to deal with Nulls in LINQ expressions?

I am wanting to know the best way for the following expression to return null if the "Orders" collection is null. Currently "First" raises an exception. I have tried "FirstOrDefault" without success.

The expression:

var myOrderItems = Model.Orders.First(o => o.Id == 1).OrderItems.ToList();

If there are no Orders then I would like "myOrderItems" to just be null.

This is an example query since I would want to apply the recommended answer to other queries.

EDIT: I currently define "Orders" in the ViewModel as:

List<Orders> _myOrders;

Possibly it should be defined as:

List<Orders> _myOrders = new List<Orders> or something else to make it empty??????? 

Upvotes: 1

Views: 136

Answers (4)

Paulo Morgado
Paulo Morgado

Reputation: 14856

List<OrderItems> myOrderItems = null;
if (Model.Orders != null)
{
    var order = Model.Orders.FirstOrDefault(o => o.Id == 1);

    if (order != null)
    {
        myOrderItems = order.OrderItems.ToList();
    }
}

Upvotes: 0

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22814

Try this:

var myOrderItems = ((Model.Orders ?? Enumerable.Empty<YourType>())
                       .FirstOrDefault(o => o.Id == 1) ?? SomeNonNullDefault).OrderItems.ToList();

Add an AsQueryable after Enumerable.Empty if you're using IQueryable and not IEnumerable.

Upvotes: 2

svick
svick

Reputation: 245028

If there are no Orders then I would like myOrderItems to just be null.

That's the wrong way to approach this. If there are no Orders, then Orders should return an empty collection, but not null. If possible, fix that. In any case, don't repeat the same mistake with myOrderItems.

Upvotes: 0

Teejay
Teejay

Reputation: 7501

var myOrderItems = Model.Orders == null ? null : Model.Orders.First(o => o.Id == 1).OrderItems.ToList();

Upvotes: 2

Related Questions