2

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?

5
  • Perhaps SelectMany is what you are looking for? Commented Nov 28, 2016 at 16:06
  • 1
    where is your property name for type List<OrderItems> in the order class? Commented Nov 28, 2016 at 16:07
  • You need to have some ops in your linq like x => x.Address.Address1== "something" Commented Nov 28, 2016 at 16:07
  • You need to determine which OrderItem you want first, then which OrderItemShipping from that and finally the Address. Commented Nov 28, 2016 at 16:08
  • "because I'm unable to grab the value I need" well, what value do you need? Commented Nov 28, 2016 at 16:22

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this did exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.