现在的位置: 首页 > 综合 > 正文

Select与SelectMany的区别

2012年04月07日 ⁄ 综合 ⁄ 共 941字 ⁄ 字号 评论关闭

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() 如何返回一个与源集合具有相同元素数目的集合。

Select() 的操作的概念图

下图描述 SelectMany() 如何将中间数组序列串联为一个最终结果值,其中包含每个中间数组中的每个值。

显示 SelectMany() 的操作的图。 

msdn: http://msdn.microsoft.com/zh-cn/library/bb546168.aspx#Mtps_DropDownFilterText

 

抱歉!评论已关闭.