C# Enumerable SelectMany(IEnumerable, Func>)
Description
Projects each element of a sequence to an IEnumerable, and flattens the resulting sequences into one sequence. The index of each source element is used in the projected form of that element.
Syntax
public static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, int, 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 source element; the second parameter of the function represents the index of the source element.
Example
The following code example demonstrates how to use SelectMany to perform a one-to-many projection over an array and use the index of each outer element.
/*from w w w . j a v a 2s. co m*/
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> query =
petOwners.SelectMany((petOwner, index) =>
petOwner.Pets.Select(pet => index + pet));
foreach (string pet in query)
{
Console.WriteLine(pet);
}
}
}
class PetOwner{
public string Name { get; set; }
public List<String> Pets { get; set; }
}
The code above generates the following result.