SelectMany

In this chapter you will learn:

  1. How to use SelectMany operator
  2. Select by both index and value

Get to know SelectMany operator

SelectMany concatenates subsequences into a single flat output sequence.

using System;//j  a v  a2 s  .c  om
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] fullNames = { "A B", "C D E", "F G" };

        IEnumerable<string> query = fullNames.SelectMany(name => name.Split());

        foreach(String s in query){
           Console.WriteLine(s);
        }
    }
}

The output:

The following code selects char arrays from string array for each string value.

using System;//from   ja v  a 2  s. c o m
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"Ad", "Art", "Buch", "Bush", "Car", "land"};

        IEnumerable<char> chars = presidents.SelectMany(p => p.ToArray());

        foreach (char ch in chars)
            Console.WriteLine(ch);

    }
}

Select by both index and value

using System;//from  j a  va  2s.  c o  m
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"A", "Art", "Buch", "Bush", "Carter", "land"};

        IEnumerable<char> chars = presidents
         .SelectMany((p, i) => i < 5 ? p.ToArray() : new char[] { });

        foreach (char ch in chars)
            Console.WriteLine(ch);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use SequenceEqual operator
  2. SequenceEqual with custom Comparer
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip