C# Enumerable SelectMany(IEnumerable, Func>)
Description
Projects
each element of a sequence to an IEnumerable
Syntax
public static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector
)
Parameters
TSource
- The type of the elements of source.TResult
- The type of the elements of the sequence returned by selector.source
- A sequence of values to project.selector
- A transform function to apply to each element.
Example
The following code example demonstrates how to use SelectMany to perform a one-to-many projection over an array.
/*from w ww. jav a2 s .com*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
PetOwner[] petOwners =
{ new PetOwner { Name="A",
Pets = new List<string>{ "a", "b" } },
new PetOwner { Name="B",
Pets = new List<string>{ "c", "d" } },
new PetOwner { Name="C",
Pets = new List<string>{ "e", "f" } } };
IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets);
foreach (string pet in query1)
{
Console.WriteLine(pet);
}
IEnumerable<List<String>> query2 =
petOwners.Select(petOwner => petOwner.Pets);
foreach (List<String> petList in query2)
{
foreach (string pet in petList)
{
Console.WriteLine(pet);
}
}
}
}
class PetOwner{
public string Name { get; set; }
public List<String> Pets { get; set; }
}
The code above generates the following result.