简体   繁体   中英

Get a IEnumerable<T> from a IEnumerable<IEnumerable<T>>

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM