In LINQ, you can create your own custom aggregation operation using the Aggregate method. This method allows you to perform a custom aggregation operation on the values of a collection or a sequence. It does not support query syntax in C# and VB.Net languages but can support method syntax in both languages. It present in both the Queryable and Enumerable class. This method is overloaded in 3 different ways:
- Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>): This method is used to apply an accumulator function over a sequence. 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>): This method apply an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.
- Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>): This method apply an accumulator function over a sequence.
Explanation: In var result = sequence.Aggregate((q1, q2) => q1+ “-“+q2);, first it takes Geeks and gfg elements and perform a concatenation operation in between them, then it takes this result to concatenate with GeeksfoGeeks element. Again this result is used to perform the concatenation operation with GFG element and at last the final result is stored in the result variable. Or simply it is like: (((Geeks-gfg)-GeeksforGeeks)-GFG)
Total salary of the Employees: 220000
Explanation: The working of Aggregate method in this var res = emp.Select(e => e.emp_salary).Aggregate((x, y)=> x+y); statement is:
(20000, 30000) => 20000 + 30000;
(50000, 40000) => 50000 + 40000;
(50000, 40000) => 130000 + 40000;
(130000, 40000) => 170000 + 40000;
(170000, 50000) => 170000 + 50000;
final value store in res is 220000
- LINQ | Aggregate Operators | LongCount
- LINQ | How to find the sum of the given Sequence?
- LINQ | How to find average of the given sequence?
- LINQ | How to find maximum value of the given sequence?
- LINQ | How to find minimum value of the given sequence?
- Count the number of element present in the sequence in LINQ?
- LINQ | Set Operator | Except
- LINQ | Let Keyword
- What is Query in LINQ?
- LINQ | Partition Operator | Take
- Aggregation Function in LINQ
- LINQ | Method Syntax
- LINQ | Set Operator | Union
- LINQ | Quantifier Operator | Any
- LINQ | Set Operator | Intersect
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.