Enumerable.Aggregate Метод

Определение

Перегрузки

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

Применяет к последовательности агрегатную функцию. Указанное начальное значение служит исходным значением для агрегатной операции, а указанная функция используется для выбора результирующего значения.

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

Применяет к последовательности агрегатную функцию. Указанное начальное значение используется в качестве исходного значения агрегатной операции.

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

Применяет к последовательности агрегатную функцию.

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

Применяет к последовательности агрегатную функцию. Указанное начальное значение служит исходным значением для агрегатной операции, а указанная функция используется для выбора результирующего значения.

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

Параметры типа

TSource

Тип элементов source.

TAccumulate

Тип агрегатного значения.

TResult

Тип результирующего значения.

Параметры

source
IEnumerable<TSource>

Объект IEnumerable<T>, для которого выполняется статистическая операция.

seed
TAccumulate

Начальное агрегатное значение.

func
Func<TAccumulate,TSource,TAccumulate>

Агрегатная функция, вызываемая для каждого элемента.

resultSelector
Func<TAccumulate,TResult>

Функция, преобразующая конечное агрегатное значение в результирующее значение.

Возвращаемое значение

TResult

Преобразованное конечное агрегатное значение.

Исключения

Параметр source, func или resultSelector имеет значение null.

Примеры

В следующем примере кода показано, как использовать Aggregate для применения функции аккумулятора и селектора результатов.

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

Комментарии

Метод Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) упрощает вычисление последовательности значений. Этот метод работает путем вызова func один раз для каждого элемента в source. func При каждом вызове Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) передает элемент из последовательности и агрегированное значение (в качестве первого аргумента в func). Значение seed параметра используется в качестве начального агрегатного значения. Результат func заменяет предыдущее агрегированное значение. Окончательный func результат передается в resultSelector , чтобы получить окончательный результат .Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>)

Для упрощения общих операций агрегирования стандартные операторы запросов также включают метод подсчета общего назначения , Countи четыре метода агрегирования чисел, а именно Min, Max, Sumи Average.

Применяется к

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

Применяет к последовательности агрегатную функцию. Указанное начальное значение используется в качестве исходного значения агрегатной операции.

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

Параметры типа

TSource

Тип элементов source.

TAccumulate

Тип агрегатного значения.

Параметры

source
IEnumerable<TSource>

Объект IEnumerable<T>, для которого выполняется статистическая операция.

seed
TAccumulate

Начальное агрегатное значение.

func
Func<TAccumulate,TSource,TAccumulate>

Агрегатная функция, вызываемая для каждого элемента.

Возвращаемое значение

TAccumulate

Конечное агрегатное значение.

Исключения

Параметр source или func имеет значение null.

Примеры

В следующем примере кода показано, как использовать Aggregate для применения функции аккумулятора и начального значения.

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

Комментарии

Метод Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) упрощает вычисление последовательности значений. Этот метод работает путем вызова func один раз для каждого элемента в source. func При каждом вызове Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) передает элемент из последовательности и агрегированное значение (в качестве первого аргумента в func). Значение seed параметра используется в качестве начального агрегатного значения. Результат func заменяет предыдущее агрегированное значение. Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)возвращает окончательный результат .func

Для упрощения общих операций агрегирования стандартные операторы запросов также включают метод подсчета общего назначения , Countи четыре метода агрегирования чисел, а именно Min, Max, Sumи Average.

Применяется к

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

Применяет к последовательности агрегатную функцию.

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

Параметры типа

TSource

Тип элементов source.

Параметры

source
IEnumerable<TSource>

Объект IEnumerable<T>, для которого выполняется статистическая операция.

func
Func<TSource,TSource,TSource>

Агрегатная функция, вызываемая для каждого элемента.

Возвращаемое значение

TSource

Конечное агрегатное значение.

Исключения

Параметр source или func имеет значение null.

Последовательность source не содержит элементов.

Примеры

В следующем примере кода показано, как изменить порядок слов в строке с помощью 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

Комментарии

Метод Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) упрощает вычисление последовательности значений. Этот метод работает путем вызова func по одному разу для каждого элемента в , source кроме первого. func При каждом вызове Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) передает элемент из последовательности и агрегированное значение (в качестве первого аргумента в func). Первый элемент используется source в качестве начального агрегатного значения. Результат func заменяет предыдущее агрегированное значение. Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)возвращает окончательный результат .func

Эта перегрузка Aggregate метода подходит не для всех случаев, так как в качестве начального агрегатного source значения используется первый элемент . Следует выбрать другую перегрузку, если возвращаемое значение должно включать только элементы , source соответствующие определенному условию. Например, эта перегрузка не является надежной, если вы хотите вычислить сумму четных чисел в source. Результат будет неправильным, если первый элемент является нечетным, а не четным.

Для упрощения общих операций агрегирования стандартные операторы запросов также включают метод подсчета общего назначения , Countи четыре метода агрегирования чисел, а именно Min, Max, Sumи Average.

Применяется к