0

I have a List<> of objects that contains another List<> of objects and I'm trying to get a distinct list of values from a property of the nested List<> object. Is there a clean Lambda way of doing this?

class Order
{
    public List<Product> Products { get; set; }
}

class Product
{
    public string ID { get; set; }
}
    
// create a list of all orders from today.
List<Order> orders = GetOrders(DateTime.Now);

// i know this is way wrong, but hopefully expresses what I'm trying to do.
List<string> productIds = orders.Products.Distinct(x => x.ID).ToList();

1 Answer 1

2

You have to use SelectMany. I think this will work for you.

List<string> productIds = orders.SelectMany(o => o.Products).Select(p => p.ID).Distinct();    
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfect. Thanks for the link as well, was helpful seeing all the other methods available.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.