是否有Queryable.SelectMany()方法的C#LINQ语法?

Bri*_*sey 80 c# linq iqueryable keyword

使用C#LINQ语法编写查询时,有没有办法使用关键字语法中的Queryable.SelectMany方法?

对于

string[] text = { "Albert was here", 
                  "Burke slept late", 
                  "Connor is happy" };
Run Code Online (Sandbox Code Playgroud)

使用流畅的方法,我可以查询

var tokens = text.SelectMany(s => s.Split(' '));
Run Code Online (Sandbox Code Playgroud)

是否有类似的查询语法

var tokens = from x in text selectmany s.Split(' ')
Run Code Online (Sandbox Code Playgroud)

dri*_*iis 113

是的,你只需重复from ... in子句:

var words = from str in text
            from word in str.Split(' ')
            select word;
Run Code Online (Sandbox Code Playgroud)

  • @BCooksey - 是的...因为你是从嵌套在第一个结果中的集合中选择的. (4认同)
  • 所有这些调用都可以由SelectMany提供服务,这非常灵活,但编译器将在Select,SelectMany之间进行选择,甚至根本不进行任何转换,具体取决于查询的形式 (3认同)

dtb*_*dtb 19

您可以使用条款中化合物:

var tokens = from s in text
             from x in s.Split(' ')
             select x;
Run Code Online (Sandbox Code Playgroud)


Jus*_*ner 14

您的查询将被重写为:

var tokens = from x in text
             from z in x.Split(' ')
             select z;
Run Code Online (Sandbox Code Playgroud)

这是一个很好的页面,其中包含几个Lambda和Query语法的并排示例:

选择许多操作员第1部分 - Zeeshan Hirani