C# Enumerable SelectMany(IEnumerable, Func>, Func)

Description

Projects each element of a sequence to an IEnumerable , flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein.

Syntax


public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
  this IEnumerable<TSource> source,
  Func<TSource, IEnumerable<TCollection>> collectionSelector,
  Func<TSource, TCollection, TResult> resultSelector
)/* w  w w . j a  va2s  .  c om*/

Parameters

  • TSource - The type of the elements of source.
  • TCollection - The type of the intermediate elements collected by collectionSelector.
  • TResult - The type of the elements of the resulting sequence.
  • source - A sequence of values to project.
  • collectionSelector - A transform function to apply to each element of the input sequence.
  • resultSelector - A transform function to apply to each element of the intermediate sequence.

Example

The following code example demonstrates how to use SelectMany to perform a one-to-many projection over an array and use a result selector function to keep each corresponding element from the source sequence in scope for the final call to Select.


/*from  w w w  . j  a  v a2s .  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" } },
          new PetOwner { Name="D", Pets = new List<string>{ "S" } } };

    var query = petOwners
        .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
        .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
        .Select(ownerAndPet =>new{
                    Owner = ownerAndPet.petOwner.Name,
                    Pet = ownerAndPet.petName
                }
        );
    foreach (var obj in query)
    {
        Console.WriteLine(obj);
    }

  }
}
    
class PetOwner{
   public string Name { get; set; }
   public List<string> Pets { get; set; }
}




















Home »
  C# Tutorial »
    System.Linq »




Enumerable