Programming4us
         
 
 
Programming

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(word);

Console.WriteLine();
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)
    Console.WriteLine(word);

// 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:
---------
The
quick
brown
fox
jumps
over
the
lazy
dog.

option 2:
---------
The
quick
brown
fox
jumps
over
the
lazy
dog.

					  

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
 
 
Most View
- Windows Server 2008 : Managing Terminal Services User Connections
- A Brief History of Legacy .NET Distributed Technologies : .NET Remoting
- SharePoint 2010 : Modify the Top or Left Navigation Bar (part 1)
- Windows Azure : Understanding Message Operations
- Windows 7 : Removing an Icon from Control Panel
- The Art of SEO : Trending, Seasonality, and Seasonal Fluctuations in Keyword Demand
- SharePoint 2010 : Organizing Information - Building an Information Architecture
- Adding iPad to the Mix
- Developing an SEO-Friendly Website : Creating an Optimal Information Architecture (part 1)
- Auditing an Existing Site to Identify SEO Problems (part 3) - Fixing an Internal Linking Problem
Top 10
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 3) - Configuring Recipient Filtering
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 2)
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 1)
- Implementing Edge Services for an Exchange Server 2007 Environment : Installing and Configuring the Edge Transport Server Components
- What's New in SharePoint 2013 (part 7) - BCS
- What's New in SharePoint 2013 (part 6) - SEARCH
- What's New in SharePoint 2013 (part 6) - WEB CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 5) - ENTERPRISE CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 4) - WORKFLOWS
- What's New in SharePoint 2013 (part 3) - REMOTE EVENTS