Is there a C# LINQ syntax for the Queryable.SelectMany() method?

21,375

Solution 1

Yes, you just repeat the from ... in clause:

var words = from str in text
            from word in str.Split(' ')
            select word;

Solution 2

You can use a Compound from Clause:

var tokens = from s in text
             from x in s.Split(' ')
             select x;

Solution 3

Your query would be re-written as:

var tokens = from x in text
             from z in x.Split(' ')
             select z;

Here's a good page that has a couple of side-by-side examples of Lambda and Query syntax:

Select Many Operator Part 1 - Zeeshan Hirani

Share:
21,375
BrianCooksey
Author by

BrianCooksey

Software architect with experience on variety of platforms.

Updated on July 08, 2022

Comments

  • BrianCooksey
    BrianCooksey almost 2 years

    When writing a query using C# LINQ syntax, is there a way to use the Queryable.SelectMany method from the keyword syntax?

    For

    string[] text = { "Albert was here", 
                      "Burke slept late", 
                      "Connor is happy" };
    

    Using fluent methods I could query

    var tokens = text.SelectMany(s => s.Split(' '));
    

    Is there a query syntax akin to

    var tokens = from x in text selectmany s.Split(' ')
    
  • Justin Niessner
    Justin Niessner almost 13 years
    @BCooksey - Yes...because you're selecting from a collection nested inside the first result.
  • Sprague
    Sprague over 11 years
    All of these calls could be serviced by SelectMany, which is hugely flexible, but the compiler will choose between Select, SelectMany and even no transformation at all, depending on the form of the query