Enumerable.SelectMany Método
Definición
Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y reduce las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.
Sobrecargas
SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) |
Proyecta cada elemento de una secuencia en IEnumerable<T>, reduce las secuencias resultantes en una única secuencia e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein. |
SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) |
Proyecta cada elemento de una secuencia en IEnumerable<T>, reduce las secuencias resultantes en una única secuencia e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein. El índice de cada elemento de origen se utiliza en el formulario proyectado intermedio de ese elemento.The index of each source element is used in the intermediate projected form of that element. |
SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) |
Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y reduce las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence. |
SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) |
Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y reduce las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T>, and flattens 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,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)
Proyecta cada elemento de una secuencia en IEnumerable<T>, reduce las secuencias resultantes en una única secuencia e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein.
public:
generic <typename TSource, typename TCollection, typename TResult>
[System::Runtime::CompilerServices::Extension]
static System::Collections::Generic::IEnumerable<TResult> ^ SelectMany(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, System::Collections::Generic::IEnumerable<TCollection> ^> ^ collectionSelector, Func<TSource, TCollection, TResult> ^ resultSelector);
public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TCollection,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,System.Collections.Generic.IEnumerable<TCollection>> collectionSelector, Func<TSource,TCollection,TResult> resultSelector);
static member SelectMany : seq<'Source> * Func<'Source, seq<'Collection>> * Func<'Source, 'Collection, 'Result> -> seq<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TCollection, TResult) (source As IEnumerable(Of TSource), collectionSelector As Func(Of TSource, IEnumerable(Of TCollection)), resultSelector As Func(Of TSource, TCollection, TResult)) As IEnumerable(Of TResult)
Parámetros de tipo
- TSource
Tipo de los elementos de source
.The type of the elements of source
.
- TCollection
Tipo de los elementos intermedios recopilados por collectionSelector
.The type of the intermediate elements collected by collectionSelector
.
- TResult
Tipo de los elementos de la secuencia resultante.The type of the elements of the resulting sequence.
Parámetros
- source
- IEnumerable<TSource>
Secuencia de valores que se va a proyectar.A sequence of values to project.
- collectionSelector
- Func<TSource,IEnumerable<TCollection>>
Una función de transformación que se va a aplicar a cada elemento de la secuencia de entrada.A transform function to apply to each element of the input sequence.
- resultSelector
- Func<TSource,TCollection,TResult>
Una función de transformación que se va a aplicar a cada elemento de la secuencia intermedia.A transform function to apply to each element of the intermediate sequence.
Devoluciones
- IEnumerable<TResult>
IEnumerable<T> cuyos elementos son el resultado de invocar la función de transformació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 origen correspondientes a un elemento de resultado.An IEnumerable<T> whose elements are the result of invoking the one-to-many transform 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>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) para realizar una proyección uno a varios en una matriz y usar una función del selector de resultados para mantener cada elemento correspondiente de la secuencia de origen en el ámbito de la llamada final a Select
.The following code example demonstrates how to use SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) 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
.
class PetOwner
{
public string Name { get; set; }
public List<string> Pets { get; set; }
}
public static void SelectManyEx3()
{
PetOwner[] petOwners =
{ new PetOwner { Name="Higa",
Pets = new List<string>{ "Scruffy", "Sam" } },
new PetOwner { Name="Ashkenazi",
Pets = new List<string>{ "Walker", "Sugar" } },
new PetOwner { Name="Price",
Pets = new List<string>{ "Scratches", "Diesel" } },
new PetOwner { Name="Hines",
Pets = new List<string>{ "Dusty" } } };
// Project the pet owner's name and the pet's name.
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
}
);
// Print the results.
foreach (var obj in query)
{
Console.WriteLine(obj);
}
}
// This code produces the following output:
//
// {Owner=Higa, Pet=Scruffy}
// {Owner=Higa, Pet=Sam}
// {Owner=Ashkenazi, Pet=Sugar}
// {Owner=Price, Pet=Scratches}
Structure PetOwner
Public Name As String
Public Pets() As String
End Structure
Sub SelectManyEx3()
' Create an array of PetOwner objects.
Dim petOwners() As PetOwner =
{New PetOwner With
{.Name = "Higa", .Pets = New String() {"Scruffy", "Sam"}},
New PetOwner With
{.Name = "Ashkenazi", .Pets = New String() {"Walker", "Sugar"}},
New PetOwner With
{.Name = "Price", .Pets = New String() {"Scratches", "Diesel"}},
New PetOwner With
{.Name = "Hines", .Pets = New String() {"Dusty"}}}
' Project an anonymous type that consists of
' the owner's name and the pet's name (string).
Dim query =
petOwners _
.SelectMany(
Function(petOwner) petOwner.Pets,
Function(petOwner, petName) New With {petOwner, petName}) _
.Where(Function(ownerAndPet) ownerAndPet.petName.StartsWith("S")) _
.Select(Function(ownerAndPet) _
New With {.Owner = ownerAndPet.petOwner.Name,
.Pet = ownerAndPet.petName
})
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.
Console.WriteLine(output.ToString())
End Sub
' This code produces the following output:
'
' Owner=Higa, Pet=Scruffy
' Owner=Higa, Pet=Sam
' Owner=Ashkenazi, Pet=Sugar
' Owner=Price, Pet=Scratches
Comentarios
Este método se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
El SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) método es útil cuando tiene que mantener los elementos de source
en el ámbito de la lógica de consulta que se produce después de la llamada a SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) .The SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) method is useful when you have to keep the elements of source
in scope for query logic that occurs after the call to SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>). Vea la sección Ejemplo para obtener un ejemplo de código.See the Example section for a code example. Si hay una relación bidireccional entre los objetos de tipo TSource
y los objetos de tipo TCollection
, es decir, si un objeto de tipo TCollection
proporciona una propiedad para recuperar el TSource
objeto que lo generó, no se necesita esta sobrecarga de SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) .If there is a bidirectional relationship between objects of type TSource
and objects of type TCollection
, that is, if an object of type TCollection
provides a property to retrieve the TSource
object that produced it, you do not need this overload of SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>). En su lugar, puede usar SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) y volver al TSource
objeto a través del TCollection
objeto.Instead, you can use SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) and navigate back to the TSource
object through the TCollection
object.
En la sintaxis de las expresiones de consulta, cada from
cláusula (Visual C#) o From
cláusula (Visual Basic) después de la inicial se convierte en una invocación de SelectMany .In query expression syntax, each from
clause (Visual C#) or From
clause (Visual Basic) after the initial one translates to an invocation of SelectMany.
Consulte también
- from (Cláusula, Referencia de C#)from clause (C# Reference)
- From (Cláusula, Visual Basic)From Clause (Visual Basic)
Se aplica a
SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)
Proyecta cada elemento de una secuencia en IEnumerable<T>, reduce las secuencias resultantes en una única secuencia e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein. El índice de cada elemento de origen se utiliza en el formulario proyectado intermedio de ese elemento.The index of each source element is used in the intermediate projected form of that element.
public:
generic <typename TSource, typename TCollection, typename TResult>
[System::Runtime::CompilerServices::Extension]
static System::Collections::Generic::IEnumerable<TResult> ^ SelectMany(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, int, System::Collections::Generic::IEnumerable<TCollection> ^> ^ collectionSelector, Func<TSource, TCollection, TResult> ^ resultSelector);
public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TCollection,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int,System.Collections.Generic.IEnumerable<TCollection>> collectionSelector, Func<TSource,TCollection,TResult> resultSelector);
static member SelectMany : seq<'Source> * Func<'Source, int, seq<'Collection>> * Func<'Source, 'Collection, 'Result> -> seq<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TCollection, TResult) (source As IEnumerable(Of TSource), collectionSelector As Func(Of TSource, Integer, IEnumerable(Of TCollection)), resultSelector As Func(Of TSource, TCollection, TResult)) As IEnumerable(Of TResult)
Parámetros de tipo
- TSource
Tipo de los elementos de source
.The type of the elements of source
.
- TCollection
Tipo de los elementos intermedios recopilados por collectionSelector
.The type of the intermediate elements collected by collectionSelector
.
- TResult
Tipo de los elementos de la secuencia resultante.The type of the elements of the resulting sequence.
Parámetros
- source
- IEnumerable<TSource>
Secuencia de valores que se va a proyectar.A sequence of values to project.
- collectionSelector
- Func<TSource,Int32,IEnumerable<TCollection>>
Función de transformación que se va a aplicar a cada elemento de origen; el segundo parámetro de la función representa el índice del elemento de origen.A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
- resultSelector
- Func<TSource,TCollection,TResult>
Una función de transformación que se va a aplicar a cada elemento de la secuencia intermedia.A transform function to apply to each element of the intermediate sequence.
Devoluciones
- IEnumerable<TResult>
IEnumerable<T> cuyos elementos son el resultado de invocar la función de transformació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 origen correspondientes a un elemento de resultado.An IEnumerable<T> whose elements are the result of invoking the one-to-many transform 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 se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
El SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) método es útil cuando tiene que mantener los elementos de source
en el ámbito de la lógica de consulta que se produce después de la llamada a SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) .The SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) method is useful when you have to keep the elements of source
in scope for query logic that occurs after the call to SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>). Vea la sección Ejemplo para obtener un ejemplo de código.See the Example section for a code example. Si hay una relación bidireccional entre los objetos de tipo TSource
y los objetos de tipo TCollection
, es decir, si un objeto de tipo TCollection
proporciona una propiedad para recuperar el TSource
objeto que lo generó, no se necesita esta sobrecarga de SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) .If there is a bidirectional relationship between objects of type TSource
and objects of type TCollection
, that is, if an object of type TCollection
provides a property to retrieve the TSource
object that produced it, you do not need this overload of SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>). En su lugar, puede usar SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) y volver al TSource
objeto a través del TCollection
objeto.Instead, you can use SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) and navigate back to the TSource
object through the TCollection
object.
Se aplica a
SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)
Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y reduce las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.
public:
generic <typename TSource, typename TResult>
[System::Runtime::CompilerServices::Extension]
static System::Collections::Generic::IEnumerable<TResult> ^ SelectMany(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, System::Collections::Generic::IEnumerable<TResult> ^> ^ selector);
public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,System.Collections.Generic.IEnumerable<TResult>> selector);
static member SelectMany : seq<'Source> * Func<'Source, seq<'Result>> -> seq<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TResult) (source As IEnumerable(Of TSource), selector As Func(Of TSource, IEnumerable(Of TResult))) As IEnumerable(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 devueltos por selector
.The type of the elements of the sequence returned by selector
.
Parámetros
- source
- IEnumerable<TSource>
Secuencia de valores que se va a proyectar.A sequence of values to project.
- selector
- Func<TSource,IEnumerable<TResult>>
Función de transformación que se va a aplicar a cada elemento.A transform function to apply to each element.
Devoluciones
- IEnumerable<TResult>
IEnumerable<T> cuyos elementos son el resultado de invocar la función de transformación uno a varios en cada elemento de la secuencia de entrada.An IEnumerable<T> whose elements are the result of invoking the one-to-many transform 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>(IEnumerable<TSource>, 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>(IEnumerable<TSource>, 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.SelectMany(petOwner => petOwner.Pets);
Console.WriteLine("Using SelectMany():");
// Only one foreach loop is required to iterate
// through the results since 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.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
Sub SelectManyEx1()
' Create an array of PetOwner objects.
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"}}}
' Call SelectMany() to gather all pets into a "flat" sequence.
Dim query1 As IEnumerable(Of String) =
petOwners.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 demonstrates how to use Select() instead
' of SelectMany() to get the same result.
Dim query2 As IEnumerable(Of String()) =
petOwners.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.
Console.WriteLine(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 se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
El SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) método enumera la secuencia de entrada, utiliza una función de transformación para asignar cada elemento a un IEnumerable<T> objeto y, a continuación, enumera y produce los elementos de cada uno de estos IEnumerable<T> objetos.The SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) method enumerates the input sequence, uses a transform function to map each element to an IEnumerable<T>, and then enumerates and yields the elements of each such IEnumerable<T> object. Es decir, se invoca para cada elemento de source
, selector
y se devuelve una secuencia de valores.That is, for each element of source
, selector
is invoked and a sequence of values is returned. SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) después, reduce esta colección bidimensional de colecciones a una unidimensional y la IEnumerable<T> devuelve.SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) then flattens this two-dimensional collection of collections into a one-dimensional IEnumerable<T> and returns it. Por ejemplo, si una consulta utiliza SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) para obtener los pedidos (de tipo Order
) de cada cliente en una base de datos, el resultado es de tipo IEnumerable<Order>
en C# o IEnumerable(Of Order)
en Visual Basic.For example, if a query uses SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) to obtain the orders (of type Order
) for each customer in a database, the result is of type IEnumerable<Order>
in C# or IEnumerable(Of Order)
in Visual Basic. Si en su lugar la consulta utiliza Select para obtener los pedidos, la colección de colecciones de pedidos no se combina y el resultado es de tipo IEnumerable<List<Order>>
en C# o IEnumerable(Of List(Of Order))
en Visual Basic.If instead the query uses Select to obtain the orders, the collection of collections of orders is not combined and the result is of type IEnumerable<List<Order>>
in C# or IEnumerable(Of List(Of Order))
in Visual Basic.
En la sintaxis de las expresiones de consulta, cada from
cláusula (Visual C#) o From
cláusula (Visual Basic) después de la inicial se convierte en una invocación de SelectMany .In query expression syntax, each from
clause (Visual C#) or From
clause (Visual Basic) after the initial one translates to an invocation of SelectMany.
Consulte también
- from (Cláusula, Referencia de C#)from clause (C# Reference)
- From (Cláusula, Visual Basic)From Clause (Visual Basic)
Se aplica a
SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>)
Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y reduce las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T>, and flattens 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::Collections::Generic::IEnumerable<TResult> ^ SelectMany(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, int, System::Collections::Generic::IEnumerable<TResult> ^> ^ selector);
public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int,System.Collections.Generic.IEnumerable<TResult>> selector);
static member SelectMany : seq<'Source> * Func<'Source, int, seq<'Result>> -> seq<'Result>
<Extension()>
Public Function SelectMany(Of TSource, TResult) (source As IEnumerable(Of TSource), selector As Func(Of TSource, Integer, IEnumerable(Of TResult))) As IEnumerable(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 devueltos por selector
.The type of the elements of the sequence returned by selector
.
Parámetros
- source
- IEnumerable<TSource>
Secuencia de valores que se va a proyectar.A sequence of values to project.
- selector
- Func<TSource,Int32,IEnumerable<TResult>>
Función de transformación que se va a aplicar a cada elemento de origen; el segundo parámetro de la función representa el índice del elemento de origen.A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
Devoluciones
- IEnumerable<TResult>
IEnumerable<T> cuyos elementos son el resultado de invocar la función de transformación uno a varios en cada elemento de una secuencia de entrada.An IEnumerable<T> whose elements are the result of invoking the one-to-many transform function on each element of an 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>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) para realizar una proyección uno a varios en una matriz y usar el índice de cada elemento externo.The following code example demonstrates how to use SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) to perform a one-to-many projection over an array and use the index of each outer 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" } } };
// Project the items in the array by appending the index
// of each PetOwner to each pet's name in that petOwner's
// array of pets.
IEnumerable<string> query =
petOwners.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
Sub SelectManyEx2()
' Create an array of PetOwner objects.
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"}}}
' Project the items in the array by appending the index
' of each PetOwner to each pet's name in that petOwner's
' array of pets.
Dim query As IEnumerable(Of String) =
petOwners.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.
Console.WriteLine(output.ToString())
End Sub
Comentarios
Este método se implementa mediante la ejecución aplazada.This method is implemented by using deferred execution. El valor devuelto inmediato es un objeto que almacena toda la información necesaria para realizar la acción.The immediate return value is an object that stores all the information that is required to perform the action. La consulta representada por este método no se ejecuta hasta que el objeto se enumera mediante una llamada a su GetEnumerator
método directamente o mediante foreach
en Visual C# o For Each
en Visual Basic.The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
El SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) método enumera la secuencia de entrada, utiliza una función de transformación para asignar cada elemento a un IEnumerable<T> objeto y, a continuación, enumera y produce los elementos de cada uno de estos IEnumerable<T> objetos.The SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) method enumerates the input sequence, uses a transform function to map each element to an IEnumerable<T>, and then enumerates and yields the elements of each such IEnumerable<T> object. Es decir, se invoca para cada elemento de source
, selector
y se devuelve una secuencia de valores.That is, for each element of source
, selector
is invoked and a sequence of values is returned. SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) después, reduce esta colección bidimensional de colecciones a una unidimensional y la IEnumerable<T> devuelve.SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) then flattens this two-dimensional collection of collections into a one-dimensional IEnumerable<T> and returns it. Por ejemplo, si una consulta utiliza SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) para obtener los pedidos (de tipo Order
) de cada cliente en una base de datos, el resultado es de tipo IEnumerable<Order>
en C# o IEnumerable(Of Order)
en Visual Basic.For example, if a query uses SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) to obtain the orders (of type Order
) for each customer in a database, the result is of type IEnumerable<Order>
in C# or IEnumerable(Of Order)
in Visual Basic. Si en su lugar la consulta utiliza Select para obtener los pedidos, la colección de colecciones de pedidos no se combina y el resultado es de tipo IEnumerable<List<Order>>
en C# o IEnumerable(Of List(Of Order))
en Visual Basic.If instead the query uses Select to obtain the orders, the collection of collections of orders is not combined and the result is of type IEnumerable<List<Order>>
in C# or IEnumerable(Of List(Of Order))
in Visual Basic.
Primer argumento que selector
representa el elemento que se va a procesar.The first argument to selector
represents the element to process. El segundo argumento de selector
representa el índice de base cero de ese elemento en la secuencia de origen.The second argument to selector
represents the zero-based index of that element in the source sequence. Esto puede ser útil si los elementos están en un orden conocido y desea hacer algo con un elemento en un índice determinado, por ejemplo.This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. También puede ser útil si desea recuperar el índice de uno o más elementos.It can also be useful if you want to retrieve the index of one or more elements.