Enumerable.Aggregate Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Sobrecargas
| Nome | Description |
|---|---|
| Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) |
Aplica uma função de acumulador em uma sequência. O valor de semente especificado é usado como o valor inicial do acumulador e a função especificada é usada para selecionar o valor do resultado. |
| Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) |
Aplica uma função de acumulador em uma sequência. O valor de semente especificado é usado como o valor inicial do acumulador. |
| Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) |
Aplica uma função de acumulador em uma sequência. |
Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>)
Aplica uma função de acumulador em uma sequência. O valor de semente especificado é usado como o valor inicial do acumulador e a função especificada é usada para selecionar o valor do resultado.
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.
- TAccumulate
O tipo do valor acumulador.
- TResult
O tipo do valor resultante.
Parâmetros
- source
- IEnumerable<TSource>
Um IEnumerable<T> para agregar.
- seed
- TAccumulate
O valor inicial do acumulador.
- func
- Func<TAccumulate,TSource,TAccumulate>
Uma função de acumulador a ser invocada em cada elemento.
- resultSelector
- Func<TAccumulate,TResult>
Uma função para transformar o valor do acumulador final no valor do resultado.
Retornos
O valor do acumulador final transformado.
Exceções
source ou ou funcresultSelector é null.
Exemplos
O exemplo de código a seguir demonstra como usar Aggregate para aplicar uma função de acumulador e um seletor 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
Comentários
O Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) método simplifica a execução de um cálculo em uma sequência de valores. Esse método funciona chamando func uma vez para cada elemento em source. Cada vez func que é chamado, Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) passa o elemento da sequência e um valor agregado (como o primeiro argumento para func). O valor do seed parâmetro é usado como o valor de agregação inicial. O resultado substitui func o valor agregado anterior. O resultado final é func passado para resultSelector obter o resultado final de 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 método Countde contagem de finalidade geral e quatro métodos de agregação numérica, ou seja Min, Max, Sume Average.
Aplica-se a
Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)
Aplica uma função de acumulador em uma sequência. O valor de semente especificado é usado como o valor inicial do 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
O tipo dos elementos de source.
- TAccumulate
O tipo do valor acumulador.
Parâmetros
- source
- IEnumerable<TSource>
Um IEnumerable<T> para agregar.
- seed
- TAccumulate
O valor inicial do acumulador.
- func
- Func<TAccumulate,TSource,TAccumulate>
Uma função de acumulador a ser invocada em cada elemento.
Retornos
O valor final do acumulador.
Exceções
source ou func é null.
Exemplos
O exemplo de código a seguir demonstra como usar Aggregate para aplicar uma função de acumulador e usar um valor de semente.
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
Comentários
O Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) método simplifica a execução de um cálculo em uma sequência de valores. Esse método funciona chamando func uma vez para cada elemento em source. Cada vez func que é chamado, Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) passa o elemento da sequência e um valor agregado (como o primeiro argumento para func). O valor do seed parâmetro é usado como o valor de agregação inicial. O resultado substitui func o valor agregado anterior.
Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) retorna o resultado final de func.
Para simplificar as operações de agregação comuns, os operadores de consulta padrão também incluem um método Countde contagem de finalidade geral e quatro métodos de agregação numérica, ou seja Min, Max, Sume Average.
Aplica-se a
Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)
Aplica uma função de acumulador em uma sequência.
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.
Parâmetros
- source
- IEnumerable<TSource>
Um IEnumerable<T> para agregar.
- func
- Func<TSource,TSource,TSource>
Uma função de acumulador a ser invocada em cada elemento.
Retornos
O valor final do acumulador.
Exceções
source ou func é null.
source não contém elementos.
Exemplos
O exemplo de código a seguir demonstra como reverter a ordem das palavras em uma cadeia de caracteres usando 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
Comentários
O Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) método simplifica a execução de um cálculo em uma sequência de valores. Esse método funciona chamando func uma vez para cada elemento, source exceto o primeiro. Cada vez func que é chamado, Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) passa o elemento da sequência e um valor agregado (como o primeiro argumento para func). O primeiro elemento é source usado como o valor de agregação inicial. O resultado substitui func o valor agregado anterior.
Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) retorna o resultado final de func.
Essa sobrecarga do Aggregate método não é adequada para todos os casos porque usa o primeiro elemento como source o valor de agregação inicial. Você deverá escolher outra sobrecarga se o valor retornado deve incluir apenas os elementos que source atendem a uma determinada condição. Por exemplo, essa sobrecarga não será confiável se você quiser calcular a soma dos números pares em source. O resultado será incorreto se o primeiro elemento for ímpar em vez de uniforme.
Para simplificar as operações de agregação comuns, os operadores de consulta padrão também incluem um método Countde contagem de finalidade geral e quatro métodos de agregação numérica, ou seja Min, Max, Sume Average.