Linq - SelectMany Confusion

前端 未结 4 1124
半阙折子戏
半阙折子戏 2021-01-30 01:42

From what I understand from the documentation of SelectMany, one could use it to produce a (flattened) sequence of a 1-many relationship.

I have following classes

<
4条回答
  •  既然无缘
    2021-01-30 01:52

    Here is another option using SelectMany

    var customerOrders = customers.SelectMany(
      c => orders.Where(o => o.CustomerId == c.Id)
        .Select(p => new {CustomerId = c.Id, OrderDescription = p.Description}));
    

    If you use the Entity Framework or LINQ to Sql and you have an association (relationship) between the entities, then you can do so:

    var customerOrders = customers.SelectMany(
      c => c.orders
       .Select(p => new {CustomerId = c.Id, OrderDescription = p.Description}));
    

提交回复
热议问题