Linq - SelectMany Confusion

前端 未结 4 1146
半阙折子戏
半阙折子戏 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 02:00

    SelectMany() works like Select, but with that extra feature of flattening a collection that is selected. It should be used whenever you want a projection of elements of sub-collections, and don't care about the sub-collection's containing element.

    For example, let's say your domain looked like this:

    public class Customer
      {
        public int Id { get; set; }
        public string Name { get; set; }
        public List Orders { get; set; }
      }
    
      class Order
      {
        public int Id { get; set; }
        public Customer Customer { get; set; }
        public string Description { get; set; }
      }
    

    To get the same list you wanted, your Linq would look something like this:

    var customerOrders = Customers
                            .SelectMany(c=>c.Orders)
                            .Select(o=> new { CustomerId = o.Customer.Id, 
                                               OrderDescription = o.Description });
    

    ... which will produce the same result without needing the flat collection of Orders. The SelectMany takes each Customer's Orders collection and iterates through that to produce an IEnumerable from an IEnumerable.

提交回复
热议问题