Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Quick Search

Advanced Search »

Aggregate Operator

Modified: 2007/01/12 18:25 by t_magennis - Categorized as: LINQ to Objects
{TOC}
Namespace:System.Linq
Assembly:System.Core.dll
Extends:IEnumerable<T>

Back to Standard Query Operator Index


Edit

Introduction

The Aggregate operator applies a function over a sequence. The result of the previous call to the function is passed in as an argument to the function with the next element. Optionally starts with a seed value and select projection clause.

Edit

Method Signatures

// 1 - Call Function on Each Element
public static TSource Aggregate<TSource>(
    this IEnumerable<TSource> source, 
    Func<TSource, TSource, TSource> func)
 
// 2 - With Seed
public static TAccumulate Aggregate<TSource, TAccumulate>(
    this IEnumerable<TSource> source, 
    TAccumulate seed, 
    Func<TAccumulate, TSource, TAccumulate> func)
 
// 3 - With Seed and Select Projection
public static TResult Aggregate<TSource, TAccumulate, TResult>(
    this IEnumerable<TSource> source, 
    TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, 
    Func<TAccumulate, TResult> resultSelector)



Edit

Exceptions

Throws an ArgumentNullException if source or func or resultSelector is null.
Throws an InvalidOperationException if source is empty.


Edit

Pseudo-code

If source is null throw ArgumentNullException.
If func is null throw ArgumentNullException.
If source is empty throw an InvalidOperationException.


Overload 1:
Start with the first element (first value of result).
Iterate over the source elements (starting at the second element if its there, otherwise break out of this loop)
result = func( previous result, this element )
Return result.


Overload 2:
Start with the seed value (first value of result)
Iterate over the source elements (starting at the first element)
result = func( previous result, this element )
Return result.


Overload 3:
Start with the seed value (first value of result)
Iterate over the source elements (starting at the first element)
result = func( previous result, this element )
Pass in the result to the resultSelector function and return its result.


Edit

Loop Count

1 (the source sequence is always iterated one time)

Edit

Code Samples

TODO: Code sample needed.

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or ommissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain un-intentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.