Difference Between Select and SelectMany

后端 未结 17 1112
长情又很酷
长情又很酷 2020-11-22 05:21

I\'ve been searching the difference between Select and SelectMany but I haven\'t been able to find a suitable answer. I need to learn the differenc

17条回答
  •  死守一世寂寞
    2020-11-22 05:36

    Some SelectMany may not be necessary. Below 2 queries give the same result.

    Customers.Where(c=>c.Name=="Tom").SelectMany(c=>c.Orders)
    
    Orders.Where(o=>o.Customer.Name=="Tom")
    

    For 1-to-Many relationship,

    1. if Start from "1", SelectMany is needed, it flattens the many.
    2. if Start from "Many", SelectMany is not needed. (still be able to filter from "1", also this is simpler than below standard join query)

    from o in Orders
    join c in Customers on o.CustomerID equals c.ID
    where c.Name == "Tom"
    select o
    

提交回复
热议问题