PixelPaul
PixelPaul

Reputation: 2767

Linq query to get value from nested object

I need to pull a specific value from a nested object without using a foreach loop. I think the right approach here is a linq query, but I'm unable to grab the value I need. Considering the class structure:

public class Order
{
    public int OrderID { get; set; }
    public List<OrderItems> { get; set; }
}

public class OrderItems
{
    public int OrderItemID { get; set; }
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public List<OrderItemShipping> OrderItemShippings { get; set; } 
}

public class OrderItemShipping
{
    public int OrderItemShippingID { get; set; }
    public Address ShipAddress { get; set; }


public class Address
{
    public int AddressID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }
}

I want to be able to do something like:

 var shipToAddress = Order.OrderItems.OrderItemShipping.FirstOrDefault(x => x.Address.Address1);

But my syntax must not be correct, because I'm unable to grab the value I need?

Upvotes: 2

Views: 3462

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

If you need to access items of (nested) collections SelectMany is your friend:

var shipToAddress = Order.OrderItems
     .SelectMany(oi => oi.OrderItemShipping.Select(ois => ois.ShipAddress.Address1)))
     .FirstOrDefault();

Your syntax was wrong because the overload of FirstOrDefault expects a predicate(so a function that returns a bool) but you were passing: FirstOrDefault(x => x.Address.Address1).

If you need to filter it somehow("specific value from a nested object") you need to explain your requirement more precisely.

Upvotes: 3

Related Questions