Select與SelectMany的區別

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.