CSharp - LINQ SelectMany

Introduction

The SelectMany operator creates a one-to-many output projection sequence over an input sequence.

Select operator will return one output element for every input element.

SelectMany will return zero or more output elements for every input element.

Prototypes

We will cover two prototypes for SelectMany operator.

The First Select Many Prototype

public static IEnumerable<S> SelectMany<T, S>(
  this IEnumerable<T> source,
  Func<T, IEnumerable<S>> selector);

This prototype is passed an input source sequence of elements of type T and a selector method delegate.

The returned object enumerates the input source sequence, passing each element individually from the input sequence to the selector method.

The selector method returns an object that, when enumerated, yields zero or more elements of type S in an intermediate output sequence.

The SelectMany operator will return the concatenated output sequences from each call to your selector method.

The Second SelectMany Prototype

public static IEnumerable<S> SelectMany<T, S>(
  this IEnumerable<T> source,
  Func<T, int, IEnumerable<S>> selector);

The second prototype has a zero-based index of the element in the input sequence passed to your selector method.

Exceptions

ArgumentNullException is thrown if any of the arguments are null.

The following code shows an example calling the first prototype.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program// w ww.j  av  a 2s  . c o m
{
    static void Main(string[] args)
    {
          string[] names = {"Python", "Java"};
    
          IEnumerable<char> chars = names.SelectMany(p => p.ToArray());
    
          foreach (char ch in chars)
            Console.WriteLine(ch);

    }
}

Result

In the example above, selector method receives a string as input, and by calling the ToArray method on that string, it returns an array of chars, which is the output.

For a single string input, SelectMany selector method returns a sequence of characters.

The SelectMany operator concatenates each of those character sequences into a single character sequence and returns it.

Related Topics