Enumerable.Aggregate Método

Definición

Sobrecargas

Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>)

Aplica una función de acumulador a una secuencia. El valor de inicialización especificado se utiliza como valor inicial del acumulador y la función especificada se utiliza para seleccionar el valor resultante.

Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)

Aplica una función de acumulador a una secuencia. El valor de inicialización especificado se utiliza como valor de inicio del acumulador.

Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)

Aplica una función de acumulador a una secuencia.

Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>)

Aplica una función de acumulador a una secuencia. El valor de inicialización especificado se utiliza como valor inicial del acumulador y la función especificada se utiliza para seleccionar el valor resultante.

public:
generic <typename TSource, typename TAccumulate, typename TResult>
[System::Runtime::CompilerServices::Extension]
 static TResult Aggregate(System::Collections::Generic::IEnumerable<TSource> ^ source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> ^ func, Func<TAccumulate, TResult> ^ resultSelector);
public static TResult Aggregate<TSource,TAccumulate,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate,TSource,TAccumulate> func, Func<TAccumulate,TResult> resultSelector);
static member Aggregate : seq<'Source> * 'Accumulate * Func<'Accumulate, 'Source, 'Accumulate> * Func<'Accumulate, 'Result> -> 'Result
<Extension()>
Public Function Aggregate(Of TSource, TAccumulate, TResult) (source As IEnumerable(Of TSource), seed As TAccumulate, func As Func(Of TAccumulate, TSource, TAccumulate), resultSelector As Func(Of TAccumulate, TResult)) As TResult

Parámetros de tipo

TSource

Tipo de los elementos de source.

TAccumulate

Tipo del valor del acumulador.

TResult

Tipo del valor resultante.

Parámetros

source
IEnumerable<TSource>

Objeto IEnumerable<T> en el que se van a agregar elementos.

seed
TAccumulate

Valor de inicio del acumulador.

func
Func<TAccumulate,TSource,TAccumulate>

Función de acumulador que se va a invocar en cada elemento.

resultSelector
Func<TAccumulate,TResult>

Función que va a transformar el valor final del acumulador en el valor del resultado.

Devoluciones

TResult

El valor final del acumulador transformado.

Excepciones

source o func o resultSelector es null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar Aggregate para aplicar una función de acumulador y un selector de resultados.

string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };

// Determine whether any string in the array is longer than "banana".
string longestName =
    fruits.Aggregate("banana",
                    (longest, next) =>
                        next.Length > longest.Length ? next : longest,
    // Return the final result as an upper case string.
                    fruit => fruit.ToUpper());

Console.WriteLine(
    "The fruit with the longest name is {0}.",
    longestName);

// This code produces the following output:
//
// The fruit with the longest name is PASSIONFRUIT.
Sub AggregateEx3()
    Dim fruits() As String =
    {"apple", "mango", "orange", "passionfruit", "grape"}

    ' Determine whether any string in the array is longer than "banana".
    Dim longestName As String =
    fruits.Aggregate("banana",
                     Function(ByVal longest, ByVal fruit) _
                         IIf(fruit.Length > longest.Length, fruit, longest),
                     Function(ByVal fruit) fruit.ToUpper())

    ' Display the output.
    Console.WriteLine($"The fruit with the longest name is {longestName}")
End Sub

' This code produces the following output:
'
' The fruit with the longest name is PASSIONFRUIT

Comentarios

El Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) método facilita la realización de un cálculo en una secuencia de valores. Este método funciona llamando una func vez para cada elemento de source. Cada vez func que se llama a , Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) pasa el elemento de la secuencia y un valor agregado (como primer argumento a func). El valor del seed parámetro se usa como valor agregado inicial. El resultado de func reemplaza el valor agregado anterior. El resultado final de func se pasa a para resultSelector obtener el resultado final de Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>).

Para simplificar las operaciones de agregación comunes, los operadores de consulta estándar también incluyen un método de recuento de uso general, County cuatro métodos de agregación numéricos, es decirMin, , MaxSum, y Average.

Se aplica a

Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)

Aplica una función de acumulador a una secuencia. El valor de inicialización especificado se utiliza como valor de inicio del acumulador.

public:
generic <typename TSource, typename TAccumulate>
[System::Runtime::CompilerServices::Extension]
 static TAccumulate Aggregate(System::Collections::Generic::IEnumerable<TSource> ^ source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> ^ func);
public static TAccumulate Aggregate<TSource,TAccumulate> (this System.Collections.Generic.IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate,TSource,TAccumulate> func);
static member Aggregate : seq<'Source> * 'Accumulate * Func<'Accumulate, 'Source, 'Accumulate> -> 'Accumulate
<Extension()>
Public Function Aggregate(Of TSource, TAccumulate) (source As IEnumerable(Of TSource), seed As TAccumulate, func As Func(Of TAccumulate, TSource, TAccumulate)) As TAccumulate

Parámetros de tipo

TSource

Tipo de los elementos de source.

TAccumulate

Tipo del valor del acumulador.

Parámetros

source
IEnumerable<TSource>

Objeto IEnumerable<T> en el que se van a agregar elementos.

seed
TAccumulate

Valor de inicio del acumulador.

func
Func<TAccumulate,TSource,TAccumulate>

Función de acumulador que se va a invocar en cada elemento.

Devoluciones

TAccumulate

Valor final del acumulador.

Excepciones

source o func es null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar Aggregate para aplicar una función de acumulador y usar un valor de inicialización.

int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };

// Count the even numbers in the array, using a seed value of 0.
int numEven = ints.Aggregate(0, (total, next) =>
                                    next % 2 == 0 ? total + 1 : total);

Console.WriteLine("The number of even integers is: {0}", numEven);

// This code produces the following output:
//
// The number of even integers is: 6
Sub AggregateEx2()
    ' Create an array of Integers.
    Dim ints() As Integer = {4, 8, 8, 3, 9, 0, 7, 8, 2}

    ' Count the even numbers in the array, using a seed value of 0.
    Dim numEven As Integer =
    ints.Aggregate(0,
                   Function(ByVal total, ByVal number) _
                       IIf(number Mod 2 = 0, total + 1, total))

    ' Display the output.
    Console.WriteLine($"The number of even integers is {numEven}")
End Sub

' This code produces the following output:
'
'The number of even integers is 6

Comentarios

El Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) método facilita la realización de un cálculo en una secuencia de valores. Este método funciona llamando una func vez para cada elemento de source. Cada vez func que se llama a , Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) pasa el elemento de la secuencia y un valor agregado (como primer argumento a func). El valor del seed parámetro se usa como valor agregado inicial. El resultado de func reemplaza el valor agregado anterior. Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) devuelve el resultado final de func.

Para simplificar las operaciones de agregación comunes, los operadores de consulta estándar también incluyen un método de recuento de uso general, County cuatro métodos de agregación numéricos, es decirMin, , MaxSum, y Average.

Se aplica a

Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)

Aplica una función de acumulador a una secuencia.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource Aggregate(System::Collections::Generic::IEnumerable<TSource> ^ source, Func<TSource, TSource, TSource> ^ func);
public static TSource Aggregate<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TSource,TSource> func);
static member Aggregate : seq<'Source> * Func<'Source, 'Source, 'Source> -> 'Source
<Extension()>
Public Function Aggregate(Of TSource) (source As IEnumerable(Of TSource), func As Func(Of TSource, TSource, TSource)) As TSource

Parámetros de tipo

TSource

Tipo de los elementos de source.

Parámetros

source
IEnumerable<TSource>

Objeto IEnumerable<T> en el que se van a agregar elementos.

func
Func<TSource,TSource,TSource>

Función de acumulador que se va a invocar en cada elemento.

Devoluciones

TSource

Valor final del acumulador.

Excepciones

source o func es null.

source no contiene ningún elemento.

Ejemplos

En el ejemplo de código siguiente se muestra cómo invertir el orden de las palabras en una cadena mediante Aggregate.

string sentence = "the quick brown fox jumps over the lazy dog";

// Split the string into individual words.
string[] words = sentence.Split(' ');

// Prepend each word to the beginning of the
// new sentence to reverse the word order.
string reversed = words.Aggregate((workingSentence, next) =>
                                      next + " " + workingSentence);

Console.WriteLine(reversed);

// This code produces the following output:
//
// dog lazy the over jumps fox brown quick the
Sub AggregateEx1()
    Dim sentence As String =
    "the quick brown fox jumps over the lazy dog"
    ' Split the string into individual words.
    Dim words() As String = sentence.Split(" "c)
    ' Prepend each word to the beginning of the new sentence to reverse the word order.
    Dim reversed As String =
    words.Aggregate(Function(ByVal current, ByVal word) word & " " & current)

    ' Display the output.
    Console.WriteLine(reversed)
End Sub

' This code produces the following output:
'
' dog lazy the over jumps fox brown quick the

Comentarios

El Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) método facilita la realización de un cálculo en una secuencia de valores. Este método funciona llamando func una vez para cada elemento de excepto source el primero. Cada vez func que se llama a , Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) pasa el elemento de la secuencia y un valor agregado (como primer argumento a func). El primer elemento de source se usa como valor agregado inicial. El resultado de func reemplaza el valor agregado anterior. Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) devuelve el resultado final de func.

Esta sobrecarga del Aggregate método no es adecuada para todos los casos porque usa el primer elemento de source como valor agregado inicial. Debe elegir otra sobrecarga si el valor devuelto debe incluir solo los elementos de source que cumplen una condición determinada. Por ejemplo, esta sobrecarga no es confiable si desea calcular la suma de los números pares en source. El resultado será incorrecto si el primer elemento es impar en lugar de incluso.

Para simplificar las operaciones de agregación comunes, los operadores de consulta estándar también incluyen un método de recuento de uso general, County cuatro métodos de agregación numéricos, es decirMin, , MaxSum, y Average.

Se aplica a