What is an Aggregate in LINQ?

An aggregate is simply a result of an initial value that accumulates operations defined by you on its currently running value. Simply speaking, if you have a variable with an initial value, and a collection of objects, you can add whatever the class of those objects has to offer to that variable or, in other words, aggregate.
Let’s go through a simple example when we have a list of objects of a class called Person:

public class Person
{
	public string Name { get; set; }
	public char Gender { get; set; }
}

public class Registry
{
	public List Persons { get; set; }
}

Say, we instantiate appropriate objects and we have a

var myRegistry = new Registry();

We can now do this:

// we add Person objects here
foreach (var person in myRegistry)
{
	Console.WriteLine(person.Name);
}
This will output all the persons we have added. Now, what if you want to only show persons based on their gender?

You can use the code below to show only a specific gender

foreach (var person in myRegistry)
{
	if (person.Gender == gender) { Console.WriteLine(person.Name); }
}

Or you can use this to do the same thing:

var result = persons.Aggregate("", (running, obj) => running + (obj.Gender == gender ? obj.Name + "\n" : ""));

Our first parameter, an empty string, is the initial value. Our second parameter is a lamda expression designating what we already have as the first parameter and an object we are taking in as the second parameter. It is now for us to decide how we interpret the input and what it is we want as a result. In our case, we want to take what we already have and add a person’s name only if the gender is the one that is selected. The return from the lambda expression will be the new value of running. And, in the end, it will be just like our foreach loop.
If you are thrown off a bit – just try it yourself. The best way to learn is not when someone explains it, but when you practice.

This entry was posted in LINQ and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *