How to Use LINQ Aggregate to on a C# List

Hello, and welcome to the first blog post on LINQ Exchange. My goal for this blog is to cover each LINQ extension, describe it, and show examples of how and why you might use it. I will probably be going in alphabetical order, at least in the beginning. If you have a request for a specific extension, or if something warrants additional commentary, then I will happily post another blog entry for it.

Today, we will be discussing Aggregate.

Syntax:

 Aggregate<(Of TSource>)(IEnumerable<(Of TSource>), Func<(Of TSource, TSource, TSource>))

 

First, the Microsoft Explanation:

The Aggregate method makes it simple to perform a calculation over a
sequence of values. This method works by calling func one time for each element in source. Each time func is
called, Aggregate passes both the element from the sequence and an
aggregated value (as the first argument to func).
The first element of source is used as the initial
aggregate value. The result of func replaces the
previous aggregated value. Aggregate returns the final result of func.

So, basically Aggregate allows you to loop through an IENumerable list and add the values in the list to produce a final result. The final result is of the same type as the IENumerable items. 

The example below (Example 1) demonstrates a simple Aggregate use on a List<int>. 

Example 1:

List<int> SampleList = new List<int>() { 1, 1, 2, 3, 5, 8, 13 };
int AggCount = SampleList.Aggregate((counter, listItem) => counter += listItem);
Console.WriteLine(string.Format("Aggregate count is: {0}", AggCount));

// Outputs:
// Aggregate count is: 33

As you can see in the example, each time through the loop, counter is incremented by the value of listItem. listItem is the item in the list being iterated, while counter holds the final return value.

Why can't I just use Sum? Well, you can. But, the power of Aggregate comes when you want to do more than just add the integer values of a list. I'm going to borrow a Microsoft example so you can see what I mean:

Example 2:

string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words.

string[] words = sentence.Split(' ');
// Join each word to the beginning of the new sentence to reverse the word oder.

string reversed = words.Aggregate(( workingSentence, next) => next + " " + workingSentence);
Console.WriteLine(reversed);
/*
This code produces the following output:

dog lazy the over jumps fox brown quick the
*/

As you can see, with a little ingenuity, Aggregate can be used for a variety of purposes.

If have questions, comments, or suggestion, please feel to post them in the LINQ Exchange Forum

GD Star Rating
loading...
GD Star Rating
loading...
How to Use LINQ Aggregate to on a C# List, 4.4 out of 5 based on 12 ratings
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply