Get a IEnumerable<T> from a IEnumerable<IEnumerable<T>>
-
04-07-2019 - |
Question
public class Item { ... }
public class Order
{
public List<Item> Items
...
}
public class Customer
{
public List<Order> Orders
...
}
Now, using LINQ I need to get all items that a customer bought. How can I?
I tried something like var items = from o in cust.Orders select o.Items;
but result is IEnuberable<List<Item>>
and I wanna just one IEnumerable<Item>
.
I'm asking here to try to avoid coding 2 loops.
Solution
You need SelectMany
, which is represented in query expressions as second (and subsequent) from
clauses:
var items = from order in customer.Orders
from item in order.Items
select item;
Alternatively, to ignore query expressions:
var items = customer.Orders.SelectMany(order => order.Items);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow