Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Aggregate() method
The Aggregate() method in C# applies an accumulator function over a sequence of elements. It processes each element in the collection and combines them into a single result using a specified function. This method is part of LINQ and provides a powerful way to perform custom aggregation operations.
Syntax
The Aggregate() method has three main overloads −
// Simple aggregation without seed TSource Aggregate<TSource>(Func<TSource, TSource, TSource> func) // Aggregation with seed value TAccumulate Aggregate<TSource, TAccumulate>(TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func) // Aggregation with seed and result selector TResult Aggregate<TSource, TAccumulate, TResult>(TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
Parameters
seed − The initial accumulator value (optional).
func − An accumulator function to apply on each element.
resultSelector − A function to transform the final accumulator value (optional).
Using Aggregate() with Seed Value
This example finds the longest string from an array, comparing against a seed value −
using System;
using System.Linq;
class Demo {
static void Main() {
string[] arr = { "DemoOne", "DemoTwo", "DemoThree", "DemoFour"};
string res = arr.AsQueryable().Aggregate("DemoFive", (longest, next) => next.Length > longest.Length ? next : longest, str => str.ToLower());
Console.WriteLine("The string with more number of characters: {0}", res);
}
}
The output of the above code is −
The string with more number of characters: demothree
Using Aggregate() for Mathematical Operations
The Aggregate() method is commonly used for mathematical calculations like sum, product, or finding maximum values −
using System;
using System.Linq;
class MathOperations {
static void Main() {
int[] numbers = { 1, 2, 3, 4, 5 };
// Calculate product of all numbers
int product = numbers.Aggregate((acc, num) => acc * num);
Console.WriteLine("Product: " + product);
// Calculate sum with seed value
int sum = numbers.Aggregate(10, (acc, num) => acc + num);
Console.WriteLine("Sum with seed 10: " + sum);
// Find maximum value
int max = numbers.Aggregate((acc, num) => num > acc ? num : acc);
Console.WriteLine("Maximum: " + max);
}
}
The output of the above code is −
Product: 120 Sum with seed 10: 25 Maximum: 5
Using Aggregate() for String Concatenation
You can use Aggregate() to build strings by concatenating elements with custom formatting −
using System;
using System.Linq;
class StringAggregation {
static void Main() {
string[] words = { "Hello", "World", "from", "C#" };
// Simple concatenation
string sentence = words.Aggregate((acc, word) => acc + " " + word);
Console.WriteLine("Sentence: " + sentence);
// With seed and result selector
string formatted = words.Aggregate("Result:", (acc, word) => acc + " [" + word + "]", result => result.ToUpper());
Console.WriteLine("Formatted: " + formatted);
}
}
The output of the above code is −
Sentence: Hello World from C# Formatted: RESULT: [HELLO] [WORLD] [FROM] [C#]
Conclusion
The Aggregate() method provides flexible aggregation capabilities in C# LINQ. It allows you to apply custom logic to combine elements in a sequence, with optional seed values and result transformation functions for complex scenarios.
