LINQ to Objects : How to Return Elements When the Result Is a Sequence (Select Many)

3/22/2012 11:20:22 AM
The SelectMany standard query operator flattens out any IEnumerable<T> result elements, returning each element individually from those enumerable sources before moving onto the next element in the result sequence. In contrast, the Select extension method would stop at the first level and return the IEnumerable<T> element itself.

Listing 1 demonstrates how SelectMany differs from Select, with each variation aiming to retrieve each individual word within a set of phrase strings. To retrieve the words in Option 1, a sub for loop is required, but SelectMany automatically performs this subiteration of the original result collection, as shown in Option 2. Option 3 demonstrates that the same result can be achieved using multiple from statements in a query expression (which maps the query to use SelectMany operator behind the scenes). The Console output is shown in Output 1.

Listing 1. Select versus SelectMany—SelectMany drills into an IEnumerable result, returning its elements—see Output 1
string[] sentence = new string[] { "The quick brown",
    "fox jumps over", "the lazy dog."};

Console.WriteLine("option 1:"); Console.WriteLine("---------");

// option 1: Select returns three string[]'s with
// three strings in each.
IEnumerable<string[]> words1 =
    sentence.Select(w => w.Split(' '));

// to get each word, we have to use two foreach loops
foreach (string[] segment in words1)
    foreach (string word in segment)

Console.WriteLine("option 2:"); Console.WriteLine("---------");

// option 2: SelectMany returns nine strings
// (sub-iterates the Select result)
IEnumerable<string> words2 =
    sentence.SelectMany(segment => segment.Split(' '));

// with SelectMany we have every string individually
foreach (var word in words2)

// option 3: identical to Opt 2 above written using
// the Query Expression syntax (multiple froms)
IEnumerable<string> words3 =
    from segment in sentence
    from word in segment.Split(' ')
    select word;


Output 1.
option 1:

option 2:


How does the SelectMany extension method work? It creates a nested foreach loop over the original result, returning each subelement using yield return statements. A close facsimile of the code behind SelectMany takes the following form:

static IEnumerable<S> SelectManyIterator<T, S>(
    this IEnumerable<T> source,
    Func<T, IEnumerable<S>> selector)
    foreach (T element in source)
        foreach (S subElement in selector(element))
            yield return subElement;
Other -----------------
- LINQ to Objects : How to Change the Return Type (Select Projection)
- A Technical Overview of the Mobile Web : OTHER MOBILE TECHNOLOGIES
- A Technical Overview of the Mobile Web : THE MOBILE NETWORK
- Programming WCF Services : The Response Service (part 4) - Transactions
- Programming WCF Services : The Response Service (part 3) - Queued Service-Side Programming & Response Service-Side Programming
- Programming WCF Services : The Response Service (part 2) - Client-Side Programming
- Programming WCF Services : The Response Service (part 1) - Designing a Response Service Contract
- Programming WCF Services : Queued Versus Connected Calls - Requiring Queuing
- Programming WCF Services : Queued Services - Playback Failures
- DotNetNuke Skinning : Package and Deploy
- Unit Testing in Visual Studio 2010 (part 2) - Running a battery of tests
- Unit Testing in Visual Studio 2010 (part 1) - Creating unit tests
- Microsoft ASP.NET 3.5 : AJAX-Enabled Web Services - Remote Calls via Page Methods
- Microsoft ASP.NET 3.5 : WCF Services for ASP.NET AJAX Applications
- Mobile Game Networking Essentials : Network Programming and J2ME
- Mobile Game Networking Essentials : Multiplayer Game Basics & Network Game Problems and Solutions
- Software Testing with Visual Studio Team System 2008 : Debug and running web test (part 2) - Running the test
- Software Testing with Visual Studio Team System 2008 : Debug and running web test (part 1) - Settings for .testrunconfig file
- Visual Studio Team System 2008 : Web test editor (part 3) - Toolbar properties
- Visual Studio Team System 2008 : Web test editor (part 2) - Other request properties
Popular tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8 BlackBerry Android Ipad Iphone iOS
Most View
- Programming Excel with VBA and .NET : Procedures - Properties & Events
- Windows Server 2012 : Monitoring, Tuning, and Troubleshooting Hyper-V - Using real-time monitoring tools
- Windows Server 2008 : Promote Servers as Domain Controllers
- Exchange Server 2010 : Useful Tools for an Upgrade (part 1)
- SharePoint 2010 : Excel Services - User-Defined Functions
- SharePoint 2010 : Open the Create Dialog for Lists and Libraries
- Windows Server 2008 : Using Virtualization to Increase Productivity and Facilitate Consolidation
- Designing and Optimizing Storage in an Exchange Server 2007 Environment (part 1) - When Is the Right Time to Implement NAS and SAN Devices?
- Windows 7 : Working with Users and Groups from the Command Line
- Implementing SQL Server Objects Using Managed Code (part 2)