Home > Software design >  Using C# and Lambda, how to get a distinct list from a property of a nested List<>?
Using C# and Lambda, how to get a distinct list from a property of a nested List<>?

Time:11-17

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();

CodePudding user response:

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();    
  • Related