Enumerable.Aggregate Enumerable.Aggregate Enumerable.Aggregate Enumerable.Aggregate Method

Definição

Sobrecargas

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

Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence. O valor de semente especificado é usado como o valor inicial do acumulador e a função especificada é usada para selecionar o valor do resultado.The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.

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

Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence. O valor de semente especificado é usado como o valor inicial do acumulador.The specified seed value is used as the initial accumulator value.

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

Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence.

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

Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence. O valor de semente especificado é usado como o valor inicial do acumulador e a função especificada é usada para selecionar o valor do resultado.The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.

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

O tipo dos elementos de source.The type of the elements of source.

TAccumulate

O tipo do valor do acumulador.The type of the accumulator value.

TResult

O tipo do valor resultante.The type of the resulting value.

Parâmetros

source
IEnumerable<TSource>

Um IEnumerable<T> no qual será feita a agregação.An IEnumerable<T> to aggregate over.

seed
TAccumulate TAccumulate TAccumulate TAccumulate

O valor inicial do acumulador.The initial accumulator value.

func
Func<TAccumulate,TSource,TAccumulate>

Uma função de acumulador a ser invocada em cada elemento.An accumulator function to be invoked on each element.

resultSelector
Func<TAccumulate,TResult>

Uma função para transformar o valor final do acumulador no valor de resultado.A function to transform the final accumulator value into the result value.

Retornos

TResult TResult TResult TResult

O valor final do acumulador transformado.The transformed final accumulator value.

Exceções

source, func ou resultSelector é null.source or func or resultSelector is null.

Exemplos

O exemplo de código a seguir demonstra como Aggregate usar o para aplicar uma função de acumulador e um seletor de resultado.The following code example demonstrates how to use Aggregate to apply an accumulator function and a result selector.

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.
    MsgBox("The fruit with the longest name is " & longestName)
End Sub

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

Comentários

O Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) método torna simples a execução de um cálculo em uma sequência de valores.The Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) method makes it simple to perform a calculation over a sequence of values. Esse método funciona chamando func uma vez para cada elemento no. sourceThis method works by calling func one time for each element in source. Cada vez func que o é Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) chamado, o passa o elemento da sequência e um valor agregado (como o primeiro argumento funcpara).Each time func is called, Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) passes both the element from the sequence and an aggregated value (as the first argument to func). O valor do seed parâmetro é usado como o valor de agregação inicial.The value of the seed parameter is used as the initial aggregate value. O resultado de func substitui o valor agregado anterior.The result of func replaces the previous aggregated value. O resultado final de func é passado para resultSelector para obter o resultado final de Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>).The final result of func is passed to resultSelector to obtain the final result of Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>).

Para simplificar as operações de agregação comuns, os operadores de consulta padrão também incluem um Countmétodo de contagem de uso geral, e Minquatro métodos de agregação numéricos, ou seja, Max Sum, e Average.To simplify common aggregation operations, the standard query operators also include a general purpose count method, Count, and four numeric aggregation methods, namely Min, Max, Sum, and Average.

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

Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence. O valor de semente especificado é usado como o valor inicial do acumulador.The specified seed value is used as the initial accumulator value.

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

O tipo dos elementos de source.The type of the elements of source.

TAccumulate

O tipo do valor do acumulador.The type of the accumulator value.

Parâmetros

source
IEnumerable<TSource>

Um IEnumerable<T> no qual será feita a agregação.An IEnumerable<T> to aggregate over.

seed
TAccumulate TAccumulate TAccumulate TAccumulate

O valor inicial do acumulador.The initial accumulator value.

func
Func<TAccumulate,TSource,TAccumulate>

Uma função de acumulador a ser invocada em cada elemento.An accumulator function to be invoked on each element.

Retornos

TAccumulate TAccumulate TAccumulate TAccumulate

O valor final do acumulador.The final accumulator value.

Exceções

Exemplos

O exemplo de código a seguir demonstra como Aggregate usar o para aplicar uma função de acumulador e usar um valor de semente.The following code example demonstrates how to use Aggregate to apply an accumulator function and use a seed value.

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.
    MsgBox("The number of even integers is " & numEven)
End Sub

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

Comentários

O Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) método torna simples a execução de um cálculo em uma sequência de valores.The Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) method makes it simple to perform a calculation over a sequence of values. Esse método funciona chamando func uma vez para cada elemento no. sourceThis method works by calling func one time for each element in source. Cada vez func que o é Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) chamado, o passa o elemento da sequência e um valor agregado (como o primeiro argumento funcpara).Each time func is called, Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) passes both the element from the sequence and an aggregated value (as the first argument to func). O valor do seed parâmetro é usado como o valor de agregação inicial.The value of the seed parameter is used as the initial aggregate value. O resultado de func substitui o valor agregado anterior.The result of func replaces the previous aggregated value. Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)Retorna o resultado final de func.Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) returns the final result of func.

Para simplificar as operações de agregação comuns, os operadores de consulta padrão também incluem um Countmétodo de contagem de uso geral, e Minquatro métodos de agregação numéricos, ou seja, Max Sum, e Average.To simplify common aggregation operations, the standard query operators also include a general purpose count method, Count, and four numeric aggregation methods, namely Min, Max, Sum, and Average.

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

Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence.

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

O tipo dos elementos de source.The type of the elements of source.

Parâmetros

source
IEnumerable<TSource>

Um IEnumerable<T> no qual será feita a agregação.An IEnumerable<T> to aggregate over.

func
Func<TSource,TSource,TSource>

Uma função de acumulador a ser invocada em cada elemento.An accumulator function to be invoked on each element.

Retornos

TSource TSource TSource TSource

O valor final do acumulador.The final accumulator value.

Exceções

Exemplos

O exemplo de código a seguir demonstra como reverter a ordem de palavras em uma cadeia de Aggregatecaracteres usando.The following code example demonstrates how to reverse the order of words in a string by using 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.
    MsgBox(reversed)
End Sub

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

Comentários

O Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) método torna simples a execução de um cálculo em uma sequência de valores.The Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) method makes it simple to perform a calculation over a sequence of values. Esse método funciona chamando func uma vez para cada elemento em source , exceto o primeiro.This method works by calling func one time for each element in source except the first one. Cada vez func que o é Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) chamado, o passa o elemento da sequência e um valor agregado (como o primeiro argumento funcpara).Each time func is called, Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) passes both the element from the sequence and an aggregated value (as the first argument to func). O primeiro elemento de source é usado como o valor de agregação inicial.The first element of source is used as the initial aggregate value. O resultado de func substitui o valor agregado anterior.The result of func replaces the previous aggregated value. Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)Retorna o resultado final de func.Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) returns the final result of func.

Essa sobrecarga do Aggregate método não é adequada para todos os casos porque ele usa o primeiro elemento source de como o valor de agregação inicial.This overload of the Aggregate method isn't suitable for all cases because it uses the first element of source as the initial aggregate value. Você deve escolher outra sobrecarga se o valor de retorno deve incluir apenas os elementos source de que atendem a uma determinada condição.You should choose another overload if the return value should include only the elements of source that meet a certain condition. Por exemplo, essa sobrecarga não será confiável se você quiser calcular a soma dos números pares em source.For example, this overload isn't reliable if you want to calculate the sum of the even numbers in source. O resultado será incorreto se o primeiro elemento for ímpar, em vez de par.The result will be incorrect if the first element is odd instead of even.

Para simplificar as operações de agregação comuns, os operadores de consulta padrão também incluem um Countmétodo de contagem de uso geral, e Minquatro métodos de agregação numéricos, ou seja, Max Sum, e Average.To simplify common aggregation operations, the standard query operators also include a general purpose count method, Count, and four numeric aggregation methods, namely Min, Max, Sum, and Average.

Aplica-se a