Reputation: 6487
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
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
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
Reputation: 245028
If there are no
Order
s then I would likemyOrderItems
to just benull
.
That's the wrong way to approach this. If there are no Order
s, then Order
s 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
Reputation: 7501
var myOrderItems = Model.Orders == null ? null : Model.Orders.First(o => o.Id == 1).OrderItems.ToList();
Upvotes: 2