Select & SelectMany 的差異為何?

資料來源:https://social.msdn.microsoft.com/Forums/vstudio/en-US/ebf4adac-8873-44f1-9def-a10912e4d2ef/what-is-the-difference-between-select-and-selectmany?forum=adodotnetentityframework

 Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i.e. nested collection.

select 通常用於取得集合中的值,可能是單一值或另一個集合

selectmany 則用於取得集合中集合的值,不是想像中查詢多個欄位的用法,因為回傳多個欄位用的是 tuple value or anonymous type這兩種方式。

回到主題,selectmany的好處在於可以直接取得巢狀集合(集合中有另一集合)中的值,讓迴圈少跑1次。

//寫法2 :總算看懂了, 因為 select 裡再包 1個select , 回傳後會變IEnumerable<IEnumerable<string>>

//如果是 selectmany 裡再包 1個select , 回傳時變成 IEnumerable<string> , 讓你少寫1次迴圈

var customerOrders_Tuple = customers.SelectMany( //SelectMany 簡化為單一序列 , 跑1次迴圈就能抓出值 . 

(cust, custIndex) => cust.Orders.Select(o => "Customer #" + (custIndex + 1) +

" has an order with OrderID " + o.OrderID));

foreach (var order in customerOrders_Tuple)

{

Console.WriteLine(order);

}

WriteLine("==Select Many=================================================");

var customerOrders_Select = customers.Select( //Select 直接回傳 序列 , 跑2次迴圈才能抓出值

(cust, custIndex) => cust.Orders.Select(o => "Customer #" + (custIndex + 1) +

" has an order with OrderID " + o.Total));

foreach (var order in customerOrders_Select)

{

foreach (var item in order)

{

Console.WriteLine(item);

}

}

WriteLine("==Select=================================================");

留言

這個網誌中的熱門文章

溪和食品有限公司 - 觀光工廠接待人員(薪約30K.免費供餐),今天投遞此份工作。

載入JavaScript code的最佳時機