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

Asked

Viewed 47 times

0

Hello, I am working with c# and I have the following situation:

  • I have 2 classes in the system, Order and ProductSold;
  • Order contains as property a List<ProductSold>;
  • In certain 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(); // ???
    }
}

In doing so, I end up having a list of lists of ProductSold. I need to merge these lists and return only one. How to proceed?

1 answer

2


To return only one list, use the Selectmany method:

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

Example no . Netfiddle by colleague Rovann Linhalis: Example

  • 2

    I put in . Netfiddle an example: https://dotnetfiddle.net/CYFmjD

  • 2

    I included in the answer your example, thanks man! I will start posting the answers with . Netfiddle also to increase the quality, thanks!

  • Kra about 3 minutes ago I found here, but thank you very much, that’s exactly what I was hunting xD

Browser other questions tagged

You are not signed in. Login or sign up in order to post.