LINQ
Aggregate
algorithm
C#
programming

LINQ Aggregate algorithm explained

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

LINQ (Language Integrated Query) is a powerful feature in .NET for querying data in a type-safe manner. Among the various operations LINQ offers, the Aggregate method is particularly potent, providing developers with the ability to perform complex reductions and accumulations over sequences. This method is flexible and can be customized to perform a wide variety of tasks by applying a sequential operation on a data collection, instead of being limited to simple operations like sums or averages.

Understanding the Aggregate Method

At its core, the Aggregate method is akin to the reduce function found in other programming paradigms. It allows you to apply a function sequentially to a collection's elements, thereby transforming the sequence into a single accumulated result. The method signature can vary, but at its simplest, it typically looks like:

csharp
1public static TAccumulate Aggregate<TSource, TAccumulate>(
2    this IEnumerable<TSource> source,
3    TAccumulate seed,
4    Func<TAccumulate, TSource, TAccumulate> func
5);

Parameters Explained

  • TSource: Type of the elements in the sequence.
  • TAccumulate: Type of the accumulated result.
  • source: The sequence of elements to aggregate.
  • seed: The initial accumulator value.
  • func: A transform function to apply to each element.

Functionality

The Aggregate method processes the sequence using the specified seed as the initial value. It then uses the provided function, func, to combine each element of the sequence with the accumulator, updating the accumulator after each iteration.

Use Cases

The Aggregate method can be used in a multitude of scenarios where transformation or reduction of data is needed. Below are some representative examples:

Example 1: Calculating Factorial

csharp
int[] numbers = { 1, 2, 3, 4, 5 };
int factorial = numbers.Aggregate(1, (acc, val) => acc * val);
// factorial: 120

Example 2: String Concatenation

csharp
string[] words = { "one", "two", "three" };
string sentence = words.Aggregate("Sentence: ", (acc, word) => acc + word + " ");
// sentence: "Sentence: one two three "

Example 3: Custom Object Aggregation

When working with complex objects, Aggregate can sum specific fields or calculate composite metrics.

csharp
1var products = new[] {
2    new { Name = "Apple", Price = 1.0, Quantity = 2 },
3    new { Name = "Banana", Price = 0.5, Quantity = 5 },
4    new { Name = "Orange", Price = 1.25, Quantity = 3 }
5};
6
7double totalRevenue = products.Aggregate(0.0, (acc, product) => acc + product.Price * product.Quantity);
8// totalRevenue: 7.25

Advanced Use: Aggregating with a Result Selector

In more complex scenarios, you might want not only to accumulate a result but also to transform it into another type. This is where an overload of Aggregate with a result selector comes into play:

csharp
1public static TResult Aggregate<TSource, TAccumulate, TResult>(
2    this IEnumerable<TSource> source,
3    TAccumulate seed,
4    Func<TAccumulate, TSource, TAccumulate> func,
5    Func<TAccumulate, TResult> resultSelector
6);

Example: Transforming to a Different Type

csharp
1int[] nums = { 1, 2, 3, 4 };
2string result = nums.Aggregate(
3    "",
4    (acc, num) => acc + num.ToString(),
5    final => $"Concatenated string: {final}"
6);
7// result: "Concatenated string: 1234"

Key Takeaways

The table below summarizes the key points of using Aggregate:

ConceptDescription
FlexibilityAggregate supports customization to handle various data types and operations.
Seed ValueProvides an initial value to start the aggregation.
Function ParameterApplies a user-defined function to accumulate results.
Result SelectorOptionally defines a transformation from the accumulated result to a final result type.

Conclusion

The LINQ Aggregate method is a robust tool in the developer’s arsenal for data aggregation. Its ability to accept a seed value and a transformation function adds a layer of flexibility that enables developers to handle both simple and sophisticated operations with ease. Understanding the Aggregate method can significantly enhance your ability to process sequences in a clean and efficient manner.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.