Поделиться через


Queryable.Aggregate Метод

Определение

Перегрузки

Имя Описание
Aggregate<TSource,TAccumulate,TResult>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>, Expression<Func<TAccumulate, TResult>>)

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

Aggregate<TSource,TAccumulate>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>)

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

Aggregate<TSource>(IQueryable<TSource>, Expression<Func<TSource,TSource,TSource>>)

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

Aggregate<TSource,TAccumulate,TResult>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>, Expression<Func<TAccumulate, TResult>>)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

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

public:
generic <typename TSource, typename TAccumulate, typename TResult>
[System::Runtime::CompilerServices::Extension]
 static TResult Aggregate(System::Linq::IQueryable<TSource> ^ source, TAccumulate seed, System::Linq::Expressions::Expression<Func<TAccumulate, TSource, TAccumulate> ^> ^ func, System::Linq::Expressions::Expression<Func<TAccumulate, TResult> ^> ^ selector);
public static TResult Aggregate<TSource,TAccumulate,TResult>(this System.Linq.IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<Func<TAccumulate,TSource,TAccumulate>> func, System.Linq.Expressions.Expression<Func<TAccumulate,TResult>> selector);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static TResult Aggregate<TSource,TAccumulate,TResult>(this System.Linq.IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<Func<TAccumulate,TSource,TAccumulate>> func, System.Linq.Expressions.Expression<Func<TAccumulate,TResult>> selector);
static member Aggregate : System.Linq.IQueryable<'Source> * 'Accumulate * System.Linq.Expressions.Expression<Func<'Accumulate, 'Source, 'Accumulate>> * System.Linq.Expressions.Expression<Func<'Accumulate, 'Result>> -> 'Result
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member Aggregate : System.Linq.IQueryable<'Source> * 'Accumulate * System.Linq.Expressions.Expression<Func<'Accumulate, 'Source, 'Accumulate>> * System.Linq.Expressions.Expression<Func<'Accumulate, 'Result>> -> 'Result
<Extension()>
Public Function Aggregate(Of TSource, TAccumulate, TResult) (source As IQueryable(Of TSource), seed As TAccumulate, func As Expression(Of Func(Of TAccumulate, TSource, TAccumulate)), selector As Expression(Of Func(Of TAccumulate, TResult))) As TResult

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

TSource

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

TAccumulate

Тип значения аккумулятора.

TResult

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

Параметры

source
IQueryable<TSource>

Последовательность для агрегирования.

seed
TAccumulate

Начальное значение аккумулятора.

func
Expression<Func<TAccumulate,TSource,TAccumulate>>

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

selector
Expression<Func<TAccumulate,TResult>>

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

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

TResult

Преобразованное окончательное значение аккумулятора.

Атрибуты

Исключения

source или funcselector есть null.

Примеры

В следующем примере кода показано, как применить Aggregate<TSource,TAccumulate,TResult>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>, Expression<Func<TAccumulate, TResult>>) функцию аккуматора и селектор результатов.

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

// Determine whether any string in the array is longer than "banana".
string longestName =
    fruits.AsQueryable().Aggregate(
    "banana",
    (longest, next) => next.Length > longest.Length ? next : longest,
    // Return the final result as an uppercase 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.
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.AsQueryable().Aggregate( _
    "banana", _
    Function(ByVal longest, ByVal fruit) IIf(fruit.Length > longest.Length, fruit, longest), _
    Function(ByVal fruit) fruit.ToUpper() _
)

MsgBox(String.Format( _
    "The fruit with the longest name is {0}.", longestName) _
)

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

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод Aggregate<TSource,TAccumulate,TResult>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>, Expression<Func<TAccumulate, TResult>>) создает объект MethodCallExpression , представляющий Aggregate<TSource,TAccumulate,TResult>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>, Expression<Func<TAccumulate, TResult>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов Aggregate<TSource,TAccumulate,TResult>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>, Expression<Func<TAccumulate, TResult>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, funcчто указанная функция применяется к каждому значению в исходной последовательности и возвращается накапливаемое значение. Параметр seed используется в качестве начального значения для накапливаемого значения, соответствующего первому параметру.func Окончательное накапливаемое значение передается для selector получения значения результата.

Чтобы упростить распространенные операции агрегирования, набор стандартных операторов запросов также включает два метода подсчета, Count а LongCountтакже четыре числовых метода агрегирования, а именно Max, MinSumи Average.

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

Aggregate<TSource,TAccumulate>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

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

public:
generic <typename TSource, typename TAccumulate>
[System::Runtime::CompilerServices::Extension]
 static TAccumulate Aggregate(System::Linq::IQueryable<TSource> ^ source, TAccumulate seed, System::Linq::Expressions::Expression<Func<TAccumulate, TSource, TAccumulate> ^> ^ func);
public static TAccumulate Aggregate<TSource,TAccumulate>(this System.Linq.IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<Func<TAccumulate,TSource,TAccumulate>> func);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static TAccumulate Aggregate<TSource,TAccumulate>(this System.Linq.IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<Func<TAccumulate,TSource,TAccumulate>> func);
static member Aggregate : System.Linq.IQueryable<'Source> * 'Accumulate * System.Linq.Expressions.Expression<Func<'Accumulate, 'Source, 'Accumulate>> -> 'Accumulate
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member Aggregate : System.Linq.IQueryable<'Source> * 'Accumulate * System.Linq.Expressions.Expression<Func<'Accumulate, 'Source, 'Accumulate>> -> 'Accumulate
<Extension()>
Public Function Aggregate(Of TSource, TAccumulate) (source As IQueryable(Of TSource), seed As TAccumulate, func As Expression(Of Func(Of TAccumulate, TSource, TAccumulate))) As TAccumulate

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

TSource

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

TAccumulate

Тип значения аккумулятора.

Параметры

source
IQueryable<TSource>

Последовательность для агрегирования.

seed
TAccumulate

Начальное значение аккумулятора.

func
Expression<Func<TAccumulate,TSource,TAccumulate>>

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

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

TAccumulate

Окончательное значение аккумулятора.

Атрибуты

Исключения

source или func есть null.

Примеры

В следующем примере кода показано, как применять Aggregate<TSource,TAccumulate>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>) функцию-накопительную функцию при предоставлении начального значения функции функции.

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.AsQueryable().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
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.AsQueryable().Aggregate( _
        0, _
        Function(ByVal total, ByVal number) _
            IIf(number Mod 2 = 0, total + 1, total) _
    )

MsgBox(String.Format("The number of even integers is: {0}", numEven))

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

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод Aggregate<TSource,TAccumulate>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>) создает объект MethodCallExpression , представляющий Aggregate<TSource,TAccumulate>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов Aggregate<TSource,TAccumulate>(IQueryable<TSource>, TAccumulate, Expression<Func<TAccumulate,TSource,TAccumulate>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, funcчто указанная функция применяется к каждому значению в исходной последовательности и возвращается накапливаемое значение. Параметр seed используется в качестве начального значения для накапливаемого значения, соответствующего первому параметру.func

Чтобы упростить распространенные операции агрегирования, набор стандартных операторов запросов также включает два метода подсчета, Count а LongCountтакже четыре числовых метода агрегирования, а именно Max, MinSumи Average.

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

Aggregate<TSource>(IQueryable<TSource>, Expression<Func<TSource,TSource,TSource>>)

Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs
Исходный код:
Queryable.cs

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

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource Aggregate(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, TSource, TSource> ^> ^ func);
public static TSource Aggregate<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TSource,TSource>> func);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static TSource Aggregate<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,TSource,TSource>> func);
static member Aggregate : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Source, 'Source>> -> 'Source
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member Aggregate : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, 'Source, 'Source>> -> 'Source
<Extension()>
Public Function Aggregate(Of TSource) (source As IQueryable(Of TSource), func As Expression(Of Func(Of TSource, TSource, TSource))) As TSource

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

TSource

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

Параметры

source
IQueryable<TSource>

Последовательность для агрегирования.

func
Expression<Func<TSource,TSource,TSource>>

Функция-аккумулятор, применяемая к каждому элементу.

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

TSource

Окончательное значение аккумулятора.

Атрибуты

Исключения

source или func есть null.

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

Примеры

В следующем примере кода показано, как создать Aggregate<TSource>(IQueryable<TSource>, Expression<Func<TSource,TSource,TSource>>) предложение из массива строк.

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

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

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

Console.WriteLine(reversed);

// This code produces the following output:
//
// dog lazy the over jumps fox brown quick the
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)

' Use Aggregate() to prepend each word to the beginning of the 
' new sentence to reverse the word order.
Dim reversed As String = _
    words.AsQueryable().Aggregate( _
        Function(ByVal workingSentence, ByVal nextWord) nextWord & " " & workingSentence _
    )

MsgBox(reversed)

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

Комментарии

Этот метод имеет по крайней мере один параметр типа, аргумент типа Expression<TDelegate> которого является одним из Func<T,TResult> типов. Для этих параметров можно передать лямбда-выражение и скомпилировать его в Expression<TDelegate>лямбда-выражение.

Метод Aggregate<TSource>(IQueryable<TSource>, Expression<Func<TSource,TSource,TSource>>) создает объект MethodCallExpression , представляющий Aggregate<TSource>(IQueryable<TSource>, Expression<Func<TSource,TSource,TSource>>) себя как созданный универсальный метод. Затем он передает MethodCallExpressionExecute<TResult>(Expression) метод IQueryProvider метода, представленного Provider свойством source параметра.

Поведение запроса, возникающее в результате выполнения дерева выражений, представляющего вызов Aggregate<TSource>(IQueryable<TSource>, Expression<Func<TSource,TSource,TSource>>) , зависит от реализации типа source параметра. Ожидаемое поведение заключается в том, funcчто указанная функция применяется к каждому значению в исходной последовательности и возвращается накапливаемое значение. Первое значение используется в качестве начального значения для накапливаемого значения source , соответствующего первому параметру в func.

Чтобы упростить распространенные операции агрегирования, набор стандартных операторов запросов также включает два метода подсчета, Count а LongCountтакже четыре числовых метода агрегирования, а именно Max, MinSumи Average.

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