Select() 和 SelectMany() 的工作都是依據源值產生一個或多個結果值。
Select() 為每個源值產生一個結果值。因此,總體結果是一個與源集合具有相同元素數目的集合。與之相反,SelectMany() 將產生單一總體結果,其中包含來自每個源值的串聯子集合。作為參數傳遞到 SelectMany() 的轉換函式必須為每個源值返回一個可枚舉值序列。然後,SelectMany() 將串聯這些可枚舉序列以建立一個大的序列。
string[] text = { "Albert was here",
"Burke slept late",
"Connor is happy" };
var tokens = text.Select(s => s.Split(' '));
foreach (string[] line in tokens)
foreach (string token in line)
Console.Write("{0}.", token);
string[] text = { "Albert was here",
"Burke slept late",
"Connor is happy" };
var tokens = text.SelectMany(s => s.Split(' '));
foreach (string token in tokens)
Console.Write("{0}.", token);
下面兩個插圖示範了這兩個方法的操作之間的概念性區別。在每種情況下,假定選取器(轉換)函數從每個源值中選擇一個由花卉資料群組成的數組。
描述 Select() 如何返回一個與源集合具有相同元素數目的集合。
描述 SelectMany() 如何將中間數組序列串聯為一個最終結果值,其中包含每個中間數組中的每個值。
msdn: http://msdn.microsoft.com/zh-cn/library/bb546168.aspx#Mtps_DropDownFilterText