SelectMany
In this chapter you will learn:
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:
Home » C# Tutorial » Linq Operators