Queryable.SelectMany Método

Definición

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y combina las secuencias resultantes en una secuencia de tipo IQueryable<T>.Projects each element of a sequence to an IEnumerable<T> and combines the resulting sequences into one sequence of type IQueryable<T>.

Sobrecargas

SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>)

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> que incorpora el índice del elemento de origen que lo generó.Projects each element of a sequence to an IEnumerable<T> that incorporates the index of the source element that produced it. Una función del selector de resultados se invoca en cada elemento de todas las secuencias intermedias y luego los valores resultantes se combinan en una única secuencia unidimensional y se devuelven.A result selector function is invoked on each element of each intermediate sequence, and the resulting values are combined into a single, one-dimensional sequence and returned.

SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>)

Proyecta cada elemento de una secuencia en IEnumerable<T> e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T> and invokes a result selector function on each element therein. Los valores resultantes de cada secuencia intermedia se combinan en una única secuencia unidimensional y se devuelven.The resulting values from each intermediate sequence are combined into a single, one-dimensional sequence and returned.

SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>)

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y combina las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and combines the resulting sequences into one sequence. El índice de cada elemento de origen se utiliza en el formulario proyectado de ese elemento.The index of each source element is used in the projected form of that element.

SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>)

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y combina las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and combines the resulting sequences into one sequence.

SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>)

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> que incorpora el índice del elemento de origen que lo generó.Projects each element of a sequence to an IEnumerable<T> that incorporates the index of the source element that produced it. Una función del selector de resultados se invoca en cada elemento de todas las secuencias intermedias y luego los valores resultantes se combinan en una única secuencia unidimensional y se devuelven.A result selector function is invoked on each element of each intermediate sequence, and the resulting values are combined into a single, one-dimensional sequence and returned.

public:
generic <typename TSource, typename TCollection, typename TResult>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TResult> ^ SelectMany(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, int, System::Collections::Generic::IEnumerable<TCollection> ^> ^> ^ collectionSelector, System::Linq::Expressions::Expression<Func<TSource, TCollection, TResult> ^> ^ resultSelector);
public static System.Linq.IQueryable<TResult> SelectMany<TSource,TCollection,TResult> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,int,System.Collections.Generic.IEnumerable<TCollection>>> collectionSelector, System.Linq.Expressions.Expression<Func<TSource,TCollection,TResult>> resultSelector);
static member SelectMany : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, int, seq<'Collection>>> * System.Linq.Expressions.Expression<Func<'Source, 'Collection, 'Result>> -> System.Linq.IQueryable<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TCollection, TResult) (source As IQueryable(Of TSource), collectionSelector As Expression(Of Func(Of TSource, Integer, IEnumerable(Of TCollection))), resultSelector As Expression(Of Func(Of TSource, TCollection, TResult))) As IQueryable(Of TResult)

Parámetros de tipo

TSource

Tipo de los elementos de source.The type of the elements of source.

TCollection

El tipo de los elementos intermedios recopilados por la función representada por collectionSelector.The type of the intermediate elements collected by the function represented by collectionSelector.

TResult

Tipo de los elementos de la secuencia resultante.The type of the elements of the resulting sequence.

Parámetros

source
IQueryable<TSource>

Secuencia de valores que se va a proyectar.A sequence of values to project.

collectionSelector
Expression<Func<TSource,Int32,IEnumerable<TCollection>>>

Función de proyección que se va a aplicar a cada elemento de la secuencia de entrada; el segundo parámetro de esta función representa el índice del elemento de origen.A projection function to apply to each element of the input sequence; the second parameter of this function represents the index of the source element.

resultSelector
Expression<Func<TSource,TCollection,TResult>>

Función de proyección que se va a aplicar a cada elemento de la secuencia intermedia.A projection function to apply to each element of each intermediate sequence.

Devoluciones

IQueryable<TResult>

IQueryable<T> cuyos elementos son el resultado de invocar la función de proyección uno a varios collectionSelector en cada elemento de source y de asignar a continuación cada uno de los elementos de la secuencia y sus elementos de source correspondientes a un elemento de resultado.An IQueryable<T> whose elements are the result of invoking the one-to-many projection function collectionSelector on each element of source and then mapping each of those sequence elements and their corresponding source element to a result element.

Excepciones

source o collectionSelector o resultSelector es null.source or collectionSelector or resultSelector is null.

Comentarios

Este método tiene al menos un parámetro de tipo Expression<TDelegate> cuyo argumento de tipo es uno de los Func<T,TResult> tipos.This method has at least one parameter of type Expression<TDelegate> whose type argument is one of the Func<T,TResult> types. Para estos parámetros, puede pasar una expresión lambda y se compilará en un Expression<TDelegate> .For these parameters, you can pass in a lambda expression and it will be compiled to an Expression<TDelegate>.

El SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) método genera un MethodCallExpression que representa la llamada a SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) sí mismo como un método genérico construido.The SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) method generates a MethodCallExpression that represents calling SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) itself as a constructed generic method. A continuación, pasa el MethodCallExpression al CreateQuery(Expression) método de IQueryProvider representado por la Provider propiedad del source parámetro.It then passes the MethodCallExpression to the CreateQuery(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

El comportamiento de la consulta que se produce como resultado de ejecutar un árbol de expresión que representa SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) la llamada depende de la implementación del tipo del source parámetro.The query behavior that occurs as a result of executing an expression tree that represents calling SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) depends on the implementation of the type of the source parameter. El comportamiento esperado es que invoca collectionSelector en cada elemento de source para proyectarlo en un formulario Enumerable.The expected behavior is that it invokes collectionSelector on each element of source to project it into an enumerable form. Cada resultado Enumerable incorpora el índice del elemento de origen.Each enumerable result incorporates the source element's index. A continuación, la función representada por resultSelector se invoca en cada elemento de cada secuencia intermedia.Then the function represented by resultSelector is invoked on each element in each intermediate sequence. Los valores resultantes se concatenan en una sola secuencia unidimensional.The resulting values are concatenated into a single, one-dimensional sequence.

Se aplica a

SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>)

Proyecta cada elemento de una secuencia en IEnumerable<T> e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T> and invokes a result selector function on each element therein. Los valores resultantes de cada secuencia intermedia se combinan en una única secuencia unidimensional y se devuelven.The resulting values from each intermediate sequence are combined into a single, one-dimensional sequence and returned.

public:
generic <typename TSource, typename TCollection, typename TResult>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TResult> ^ SelectMany(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, System::Collections::Generic::IEnumerable<TCollection> ^> ^> ^ collectionSelector, System::Linq::Expressions::Expression<Func<TSource, TCollection, TResult> ^> ^ resultSelector);
public static System.Linq.IQueryable<TResult> SelectMany<TSource,TCollection,TResult> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,System.Collections.Generic.IEnumerable<TCollection>>> collectionSelector, System.Linq.Expressions.Expression<Func<TSource,TCollection,TResult>> resultSelector);
static member SelectMany : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, seq<'Collection>>> * System.Linq.Expressions.Expression<Func<'Source, 'Collection, 'Result>> -> System.Linq.IQueryable<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TCollection, TResult) (source As IQueryable(Of TSource), collectionSelector As Expression(Of Func(Of TSource, IEnumerable(Of TCollection))), resultSelector As Expression(Of Func(Of TSource, TCollection, TResult))) As IQueryable(Of TResult)

Parámetros de tipo

TSource

Tipo de los elementos de source.The type of the elements of source.

TCollection

El tipo de los elementos intermedios recopilados por la función representada por collectionSelector.The type of the intermediate elements collected by the function represented by collectionSelector.

TResult

Tipo de los elementos de la secuencia resultante.The type of the elements of the resulting sequence.

Parámetros

source
IQueryable<TSource>

Secuencia de valores que se va a proyectar.A sequence of values to project.

collectionSelector
Expression<Func<TSource,IEnumerable<TCollection>>>

Función de proyección que se va a aplicar a cada elemento de la secuencia de entrada.A projection function to apply to each element of the input sequence.

resultSelector
Expression<Func<TSource,TCollection,TResult>>

Función de proyección que se va a aplicar a cada elemento de la secuencia intermedia.A projection function to apply to each element of each intermediate sequence.

Devoluciones

IQueryable<TResult>

IQueryable<T> cuyos elementos son el resultado de invocar la función de proyección uno a varios collectionSelector en cada elemento de source y de asignar a continuación cada uno de los elementos de la secuencia y sus elementos de source correspondientes a un elemento de resultado.An IQueryable<T> whose elements are the result of invoking the one-to-many projection function collectionSelector on each element of source and then mapping each of those sequence elements and their corresponding source element to a result element.

Excepciones

source o collectionSelector o resultSelector es null.source or collectionSelector or resultSelector is null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo utilizar SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) para realizar una proyección uno a varios en una matriz.The following code example demonstrates how to use SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) to perform a one-to-many projection over an array. En este ejemplo se usa una función del selector de resultados para mantener el elemento de origen que corresponde a cada secuencia intermedia en el ámbito de la llamada final a Select .This example uses a result selector function to keep the source element that corresponds to each intermediate sequence in scope for the final call to Select.

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

class Pet
{
    public string Name { get; set; }
    public string Breed { get; set; }
}

public static void SelectManyEx3()
{
    PetOwner[] petOwners =
        { new PetOwner { Name="Higa",
              Pets = new List<Pet>{
                  new Pet { Name="Scruffy", Breed="Poodle" },
                  new Pet { Name="Sam", Breed="Hound" } } },
          new PetOwner { Name="Ashkenazi",
              Pets = new List<Pet>{
                  new Pet { Name="Walker", Breed="Collie" },
                  new Pet { Name="Sugar", Breed="Poodle" } } },
          new PetOwner { Name="Price",
              Pets = new List<Pet>{
                  new Pet { Name="Scratches", Breed="Dachshund" },
                  new Pet { Name="Diesel", Breed="Collie" } } },
          new PetOwner { Name="Hines",
              Pets = new List<Pet>{
                  new Pet { Name="Dusty", Breed="Collie" } } }
        };

    // This query demonstrates how to obtain a sequence of
    // the names of all the pets whose breed is "Collie", while
    // keeping an association with the owner that owns the pet.
    var query =
        petOwners.AsQueryable()
        // Create a sequence of ALL the Pet objects. Then
        // project an anonymous type that consists of each
        // Pet in the new sequence and the PetOwner object
        // from the initial array that corresponds to that pet.
       .SelectMany(owner => owner.Pets,
                   (owner, pet) => new { owner, pet })
        // Filter the sequence of anonymous types to only
        // keep pets whose breed is "Collie".
        .Where(ownerAndPet => ownerAndPet.pet.Breed == "Collie")
        // Project an anonymous type that consists
        // of the pet owner's name and the pet's name.
        .Select(ownerAndPet => new
        {
            Owner = ownerAndPet.owner.Name,
            Pet = ownerAndPet.pet.Name
        });

    // Print the results.
    foreach (var obj in query)
        Console.WriteLine(obj);
}

/* This code produces the following output:

    { Owner = Ashkenazi, Pet = Walker }
    { Owner = Price, Pet = Diesel }
    { Owner = Hines, Pet = Dusty }
*/

Structure PetOwner
    Public Name As String
    Public Pets As List(Of Pet)
End Structure

Structure Pet
    Public Name As String
    Public Breed As String
End Structure

Shared Sub SelectManyEx3()
    Dim petOwners() As PetOwner = _
                {New PetOwner With {.Name = "Higa", _
                      .Pets = New List(Of Pet)(New Pet() { _
                          New Pet With {.Name = "Scruffy", .Breed = "Poodle"}, _
                          New Pet With {.Name = "Sam", .Breed = "Hound"}})}, _
                  New PetOwner With {.Name = "Ashkenazi", _
                      .Pets = New List(Of Pet)(New Pet() { _
                          New Pet With {.Name = "Walker", .Breed = "Collie"}, _
                          New Pet With {.Name = "Sugar", .Breed = "Poodle"}})}, _
                  New PetOwner With {.Name = "Price", _
                      .Pets = New List(Of Pet)(New Pet() { _
                          New Pet With {.Name = "Scratches", .Breed = "Dachshund"}, _
                          New Pet With {.Name = "Diesel", .Breed = "Collie"}})}, _
                  New PetOwner With {.Name = "Hines", _
                      .Pets = New List(Of Pet)(New Pet() { _
                          New Pet With {.Name = "Dusty", .Breed = "Collie"}})} _
                }

    ' This query demonstrates how to obtain a sequence of
    ' the names of all the pets whose breed is "Collie", while
    ' keeping an association with the owner that owns the pet.
    Dim query = petOwners.AsQueryable() _
        .SelectMany(Function(owner) owner.Pets, _
               Function(owner, pet) New With {owner, pet}) _
        .Where(Function(ownerAndPet) ownerAndPet.pet.Breed = "Collie") _
        .Select(Function(ownerAndPet) New With { _
            .Owner = ownerAndPet.owner.Name, _
            .Pet = ownerAndPet.pet.Name})

    Dim output As New System.Text.StringBuilder
    For Each obj In query
        output.AppendLine(String.Format("Owner={0}, Pet={1}", obj.Owner, obj.Pet))
    Next

    ' Display the output.
    MsgBox(output.ToString())
End Sub

' This code produces the following output:

' Owner=Ashkenazi, Pet=Walker
' Owner=Price, Pet=Diesel
' Owner=Hines, Pet=Dusty

Comentarios

Este método tiene al menos un parámetro de tipo Expression<TDelegate> cuyo argumento de tipo es uno de los Func<T,TResult> tipos.This method has at least one parameter of type Expression<TDelegate> whose type argument is one of the Func<T,TResult> types. Para estos parámetros, puede pasar una expresión lambda y se compilará en un Expression<TDelegate> .For these parameters, you can pass in a lambda expression and it will be compiled to an Expression<TDelegate>.

El SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) método genera un MethodCallExpression que representa la llamada a SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) sí mismo como un método genérico construido.The SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) method generates a MethodCallExpression that represents calling SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) itself as a constructed generic method. A continuación, pasa el MethodCallExpression al CreateQuery(Expression) método de IQueryProvider representado por la Provider propiedad del source parámetro.It then passes the MethodCallExpression to the CreateQuery(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

El comportamiento de la consulta que se produce como resultado de ejecutar un árbol de expresión que representa SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) la llamada depende de la implementación del tipo del source parámetro.The query behavior that occurs as a result of executing an expression tree that represents calling SelectMany<TSource,TCollection,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TCollection>>>, Expression<Func<TSource,TCollection,TResult>>) depends on the implementation of the type of the source parameter. El comportamiento esperado es que invoca collectionSelector en cada elemento de source para proyectarlo en un formulario Enumerable.The expected behavior is that it invokes collectionSelector on each element of source to project it into an enumerable form. A continuación, la función representada por resultSelector se invoca en cada elemento de cada secuencia intermedia.Then the function represented by resultSelector is invoked on each element in each intermediate sequence. Los valores resultantes se concatenan en una sola secuencia unidimensional.The resulting values are concatenated into a single, one-dimensional sequence.

Se aplica a

SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>)

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y combina las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and combines the resulting sequences into one sequence. El índice de cada elemento de origen se utiliza en el formulario proyectado de ese elemento.The index of each source element is used in the projected form of that element.

public:
generic <typename TSource, typename TResult>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TResult> ^ SelectMany(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, int, System::Collections::Generic::IEnumerable<TResult> ^> ^> ^ selector);
public static System.Linq.IQueryable<TResult> SelectMany<TSource,TResult> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,int,System.Collections.Generic.IEnumerable<TResult>>> selector);
static member SelectMany : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, int, seq<'Result>>> -> System.Linq.IQueryable<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TResult) (source As IQueryable(Of TSource), selector As Expression(Of Func(Of TSource, Integer, IEnumerable(Of TResult)))) As IQueryable(Of TResult)

Parámetros de tipo

TSource

Tipo de los elementos de source.The type of the elements of source.

TResult

Tipo de los elementos de la secuencia devuelta por la función representada por selector.The type of the elements of the sequence returned by the function represented by selector.

Parámetros

source
IQueryable<TSource>

Secuencia de valores que se va a proyectar.A sequence of values to project.

selector
Expression<Func<TSource,Int32,IEnumerable<TResult>>>

Función de proyección que se va a aplicar a cada elemento; el segundo parámetro de esta función representa el índice del elemento de origen.A projection function to apply to each element; the second parameter of this function represents the index of the source element.

Devoluciones

IQueryable<TResult>

IQueryable<T> cuyos elementos son el resultado de invocar una función de proyección uno a varios en cada elemento de la secuencia de entrada.An IQueryable<T> whose elements are the result of invoking a one-to-many projection function on each element of the input sequence.

Excepciones

source o selector es null.source or selector is null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo utilizar SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) para realizar una proyección uno a varios en una matriz y usar el índice de cada elemento de origen.The following code example demonstrates how to use SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) to perform a one-to-many projection over an array and use the index of each source element.

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

public static void SelectManyEx2()
{
    PetOwner[] petOwners =
        { new PetOwner { Name="Higa, Sidney",
              Pets = new List<string>{ "Scruffy", "Sam" } },
          new PetOwner { Name="Ashkenazi, Ronen",
              Pets = new List<string>{ "Walker", "Sugar" } },
          new PetOwner { Name="Price, Vernette",
              Pets = new List<string>{ "Scratches", "Diesel" } },
          new PetOwner { Name="Hines, Patrick",
              Pets = new List<string>{ "Dusty" } } };

    // For each PetOwner element in the source array,
    // project a sequence of strings where each string
    // consists of the index of the PetOwner element in the
    // source array and the name of each pet in PetOwner.Pets.
    IEnumerable<string> query =
        petOwners.AsQueryable()
        .SelectMany(
        (petOwner, index) => petOwner.Pets.Select(pet => index + pet)
        );

    foreach (string pet in query)
        Console.WriteLine(pet);
}

// This code produces the following output:
//
// 0Scruffy
// 0Sam
// 1Walker
// 1Sugar
// 2Scratches
// 2Diesel
// 3Dusty

Structure PetOwner
    Public Name As String
    Public Pets() As String
End Structure

Shared Sub SelectManyEx2()
    Dim petOwners() As PetOwner = _
        {New PetOwner With _
         {.Name = "Higa, Sidney", .Pets = New String() {"Scruffy", "Sam"}}, _
         New PetOwner With _
         {.Name = "Ashkenazi, Ronen", .Pets = New String() {"Walker", "Sugar"}}, _
         New PetOwner With _
         {.Name = "Price, Vernette", .Pets = New String() {"Scratches", "Diesel"}}, _
         New PetOwner With _
         {.Name = "Hines, Patrick", .Pets = New String() {"Dusty"}}}

    ' For each PetOwner element in the source array,
    ' project a sequence of strings where each string
    ' consists of the index of the PetOwner element in the
    ' source array and the name of each pet in PetOwner.Pets.
    Dim query As IEnumerable(Of String) = _
        petOwners.AsQueryable() _
        .SelectMany(Function(petOwner, index) petOwner.Pets.Select(Function(pet) index.ToString() + pet))

    Dim output As New System.Text.StringBuilder
    For Each pet As String In query
        output.AppendLine(pet)
    Next

    ' Display the output.
    MsgBox(output.ToString())
End Sub

' This code produces the following output:
'
' 0Scruffy
' 0Sam
' 1Walker
' 1Sugar
' 2Scratches
' 2Diesel
' 3Dusty

Comentarios

Este método tiene al menos un parámetro de tipo Expression<TDelegate> cuyo argumento de tipo es uno de los Func<T,TResult> tipos.This method has at least one parameter of type Expression<TDelegate> whose type argument is one of the Func<T,TResult> types. Para estos parámetros, puede pasar una expresión lambda y se compilará en un Expression<TDelegate> .For these parameters, you can pass in a lambda expression and it will be compiled to an Expression<TDelegate>.

El SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) método genera un MethodCallExpression que representa la llamada a SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) sí mismo como un método genérico construido.The SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) method generates a MethodCallExpression that represents calling SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) itself as a constructed generic method. A continuación, pasa el MethodCallExpression al CreateQuery(Expression) método de IQueryProvider representado por la Provider propiedad del source parámetro.It then passes the MethodCallExpression to the CreateQuery(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

El comportamiento de la consulta que se produce como resultado de ejecutar un árbol de expresión que representa SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) la llamada depende de la implementación del tipo del source parámetro.The query behavior that occurs as a result of executing an expression tree that represents calling SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,Int32,IEnumerable<TResult>>>) depends on the implementation of the type of the source parameter. El comportamiento esperado es que invoca selector en cada elemento de source para proyectarlo en un formulario Enumerable.The expected behavior is that it invokes selector on each element of source to project it into an enumerable form. Cada resultado Enumerable incorpora el índice del elemento de origen.Each enumerable result incorporates the index of the source element. A continuación, concatena los resultados enumerables en una única secuencia unidimensional.It then concatenates the enumerable results into a single, one-dimensional sequence.

Se aplica a

SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>)

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y combina las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and combines the resulting sequences into one sequence.

public:
generic <typename TSource, typename TResult>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TResult> ^ SelectMany(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, System::Collections::Generic::IEnumerable<TResult> ^> ^> ^ selector);
public static System.Linq.IQueryable<TResult> SelectMany<TSource,TResult> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,System.Collections.Generic.IEnumerable<TResult>>> selector);
static member SelectMany : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, seq<'Result>>> -> System.Linq.IQueryable<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TResult) (source As IQueryable(Of TSource), selector As Expression(Of Func(Of TSource, IEnumerable(Of TResult)))) As IQueryable(Of TResult)

Parámetros de tipo

TSource

Tipo de los elementos de source.The type of the elements of source.

TResult

Tipo de los elementos de la secuencia devuelta por la función representada por selector.The type of the elements of the sequence returned by the function represented by selector.

Parámetros

source
IQueryable<TSource>

Secuencia de valores que se va a proyectar.A sequence of values to project.

selector
Expression<Func<TSource,IEnumerable<TResult>>>

Función de proyección que se va a aplicar a cada elemento.A projection function to apply to each element.

Devoluciones

IQueryable<TResult>

IQueryable<T> cuyos elementos son el resultado de invocar una función de proyección uno a varios en cada elemento de la secuencia de entrada.An IQueryable<T> whose elements are the result of invoking a one-to-many projection function on each element of the input sequence.

Excepciones

source o selector es null.source or selector is null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo utilizar SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) para realizar una proyección uno a varios en una matriz.The following code example demonstrates how to use SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) to perform a one-to-many projection over an array.

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

public static void SelectManyEx1()
{
    PetOwner[] petOwners =
        { new PetOwner { Name="Higa, Sidney",
              Pets = new List<string>{ "Scruffy", "Sam" } },
          new PetOwner { Name="Ashkenazi, Ronen",
              Pets = new List<string>{ "Walker", "Sugar" } },
          new PetOwner { Name="Price, Vernette",
              Pets = new List<string>{ "Scratches", "Diesel" } } };

    // Query using SelectMany().
    IEnumerable<string> query1 =
        petOwners.AsQueryable().SelectMany(petOwner => petOwner.Pets);

    Console.WriteLine("Using SelectMany():");

    // Only one foreach loop is required to iterate through the
    // results because it is a one-dimensional collection.
    foreach (string pet in query1)
        Console.WriteLine(pet);

    // This code shows how to use Select() instead of SelectMany().
    IEnumerable<List<String>> query2 =
        petOwners.AsQueryable().Select(petOwner => petOwner.Pets);

    Console.WriteLine("\nUsing Select():");

    // Notice that two foreach loops are required to iterate through
    // the results because the query returns a collection of arrays.
    foreach (List<String> petList in query2)
    {
        foreach (string pet in petList)
        {
            Console.WriteLine(pet);
        }
        Console.WriteLine();
    }
}

/*
    This code produces the following output:

    Using SelectMany():
    Scruffy
    Sam
    Walker
    Sugar
    Scratches
    Diesel

    Using Select():
    Scruffy
    Sam

    Walker
    Sugar

    Scratches
    Diesel
*/

Structure PetOwner
    Public Name As String
    Public Pets() As String
End Structure

Shared Sub SelectManyEx1()
    Dim petOwners() As PetOwner = _
        {New PetOwner With _
         {.Name = "Higa, Sidney", .Pets = New String() {"Scruffy", "Sam"}}, _
         New PetOwner With _
         {.Name = "Ashkenazi, Ronen", .Pets = New String() {"Walker", "Sugar"}}, _
         New PetOwner With _
         {.Name = "Price, Vernette", .Pets = New String() {"Scratches", "Diesel"}}}

    ' Query using SelectMany().
    Dim query1 As IEnumerable(Of String) = _
                petOwners.AsQueryable().SelectMany(Function(petOwner) petOwner.Pets)

    Dim output As New System.Text.StringBuilder("Using SelectMany():" & vbCrLf)
    ' Only one foreach loop is required to iterate through 
    ' the results because it is a one-dimensional collection.
    For Each pet As String In query1
        output.AppendLine(pet)
    Next

    ' This code shows how to use Select() instead of SelectMany().
    Dim query2 As IEnumerable(Of String()) = _
                petOwners.AsQueryable().Select(Function(petOwner) petOwner.Pets)

    output.AppendLine(vbCrLf & "Using Select():")
    ' Notice that two foreach loops are required to iterate through 
    ' the results because the query returns a collection of arrays.
    For Each petArray() As String In query2
        For Each pet As String In petArray
            output.AppendLine(pet)
        Next
    Next

    ' Display the output.
    MsgBox(output.ToString())
End Sub

' This code produces the following output:

' Using SelectMany():
' Scruffy
' Sam
' Walker
' Sugar
' Scratches
' Diesel

' Using Select():
' Scruffy
' Sam
' Walker
' Sugar
' Scratches
' Diesel

Comentarios

Este método tiene al menos un parámetro de tipo Expression<TDelegate> cuyo argumento de tipo es uno de los Func<T,TResult> tipos.This method has at least one parameter of type Expression<TDelegate> whose type argument is one of the Func<T,TResult> types. Para estos parámetros, puede pasar una expresión lambda y se compilará en un Expression<TDelegate> .For these parameters, you can pass in a lambda expression and it will be compiled to an Expression<TDelegate>.

El SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) método genera un MethodCallExpression que representa la llamada a SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) sí mismo como un método genérico construido.The SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) method generates a MethodCallExpression that represents calling SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) itself as a constructed generic method. A continuación, pasa el MethodCallExpression al CreateQuery(Expression) método de IQueryProvider representado por la Provider propiedad del source parámetro.It then passes the MethodCallExpression to the CreateQuery(Expression) method of the IQueryProvider represented by the Provider property of the source parameter.

El comportamiento de la consulta que se produce como resultado de ejecutar un árbol de expresión que representa SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) la llamada depende de la implementación del tipo del source parámetro.The query behavior that occurs as a result of executing an expression tree that represents calling SelectMany<TSource,TResult>(IQueryable<TSource>, Expression<Func<TSource,IEnumerable<TResult>>>) depends on the implementation of the type of the source parameter. El comportamiento esperado es que invoca selector en cada elemento de source para proyectarlo en un formulario Enumerable.The expected behavior is that it invokes selector on each element of source to project it into an enumerable form. A continuación, concatena los resultados enumerables en una única secuencia unidimensional.It then concatenates the enumerable results into a single, one-dimensional sequence.

Se aplica a