How to merge sublists of a class and return the result using Linq and C #

0

Hello, I'm working with C # and I have the following situation:

  • I have 2 classes in the system, Order and ProductSold ;
  • Order contains as property List<ProductSold> ;
  • In a given ViewModel, I have to get a list of ProductSold that are within a List<Order> ;

The classes are as follows ...

public class ProductSold 
{ 
    ... 
}
public class Order 
{
    public List<ProductSold> ProductSolds { get; set; }
}
public class ViewModel
{
    public void getProductSolds(List<Order> orders) 
    {
        return orders.Select(x => x.ProductSolds).toList(); // ???
    }
}

Doing this, I end up with a list of ProductSold lists. I need to merge these lists and return only one. How to proceed?

    
asked by anonymous 20.07.2018 / 14:18

1 answer

2

To return a list only, use the SelectMany method:

return orders.SelectMany(x => x.ProductSolds).ToList();

Example in the .NETFiddle by colleague Rovann Linhalis: Example

    
20.07.2018 / 14:34