LINQ | How to find aggregate of the given sequence?
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 GeeksforGeeks 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) Example 2:
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
Please Login to comment...