99

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(' ')
BrianCooksey
  • 1,543
  • 1
  • 12
  • 19
  • the example needs some improvement... but I suspect it gets the basic point across. Feel free to suggest better examples. – BrianCooksey Jun 20 '11 at 17:05

3 Answers3

140

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

var words = from str in text
            from word in str.Split(' ')
            select word;
driis
  • 161,458
  • 45
  • 265
  • 341
  • 4
    @BCooksey - Yes...because you're selecting from a collection nested inside the first result. – Justin Niessner Jun 20 '11 at 17:15
  • 3
    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 – Sprague Jan 11 '13 at 14:15
24

You can use a Compound from Clause:

var tokens = from s in text
             from x in s.Split(' ')
             select x;
dtb
  • 213,145
  • 36
  • 401
  • 431
19

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

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536