How to Use LINQ Aggregate in C# for Custom Reductions
Use
LINQ Aggregate in C# to combine all elements of a collection into a single result by applying a function repeatedly. It takes a seed value and a function that specifies how to merge each element with the accumulated result.Syntax
The Aggregate method has two main forms:
source.Aggregate(func): Combines elements usingfuncwithout a seed.source.Aggregate(seed, func): Starts withseedand appliesfuncto accumulate results.
Parameters:
source: The collection to process.seed: Initial value for accumulation.func: Function that takes the accumulated value and next element, returns new accumulated value.
csharp
var result = collection.Aggregate(seed, (acc, item) => acc + item);Example
This example shows how to use Aggregate to sum numbers and to create a sentence by joining words.
csharp
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 1, 2, 3, 4 }; int sum = numbers.Aggregate(0, (acc, n) => acc + n); Console.WriteLine($"Sum: {sum}"); string[] words = { "Hello", "world", "from", "LINQ" }; string sentence = words.Aggregate((acc, w) => acc + " " + w); Console.WriteLine($"Sentence: {sentence}"); } }
Output
Sum: 10
Sentence: Hello world from LINQ
Common Pitfalls
Common mistakes when using Aggregate include:
- Not providing a seed value when the collection might be empty, causing exceptions.
- Using
Aggregatewithout a seed on empty collections throwsInvalidOperationException. - Confusing
AggregatewithSumorCountwhich are simpler for common operations.
Always consider if a seed is needed to avoid errors.
csharp
/* Wrong: Throws exception on empty array */ // int[] empty = {}; // var result = empty.Aggregate((acc, n) => acc + n); /* Right: Use seed to handle empty collections safely */ int[] empty = {}; var safeResult = empty.Aggregate(0, (acc, n) => acc + n);
Quick Reference
Tips for using LINQ Aggregate:
- Use a seed value to avoid exceptions on empty collections.
- The accumulator function takes two parameters: the current accumulated value and the next element.
- Use
Aggregatefor custom reductions beyond simple sums or counts. - Remember
Aggregatereturns a single value after processing all elements.
Key Takeaways
LINQ Aggregate combines collection elements into one value using a custom function.
Always provide a seed value to safely handle empty collections.
The accumulator function defines how to merge each element with the current result.
Aggregate is useful for custom operations beyond simple sums or counts.
Without a seed, Aggregate throws an exception on empty collections.