Introduction to Data Aggregation Methods in C#

Welcome to today's lesson! Our topic for the day is data aggregation, a crucial aspect of data analysis. Like summarizing a massive book into key points, data aggregation summarizes large amounts of data into important highlights.

By the end of this lesson, you'll be equipped with several aggregation methods to summarize data streams in C#. Let's get started!

Basic Aggregation using Built-in Functions

Let's say we have a list of integers denoting the ages of a group of people:

List<int> ages = new List<int>() { 21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22 };

Common questions we might ask are: How many people are in the group? What's their total age? Who's the youngest and the oldest? C#'s handy built-in properties and LINQ extension methods like Count, Sum, Min, and Max have our answers:

int numPeople = ages.Count; // Number of people (12)
int totalAges = ages.Sum(); // Total age (276)
int youngestAge = ages.Min(); // Youngest age (20)
int oldestAge = ages.Max(); // Oldest age (27)

// Use Sum and Count to find the average age
double averageAge = (double)ages.Sum() / ages.Count; // Result: 23

// Use Max() and Min() to find the range of ages
int ageRange = ages.Max() - ages.Min(); // Result: 7

These functions provide essential aggregation operations and are widely used with data streams.

Advanced Aggregation using For and While Loops

For deeper analysis, such as calculating the average age or range of ages manually, we can use for and while loops.

For example, using for loops, we can also find the mode or most frequent age:

List<int> ages = new List<int>() { 21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22 };

// Initialize a dictionary to store the frequency of each age
Dictionary<int, int> frequencies = new Dictionary<int, int>();

// Use a for loop to populate frequencies
foreach (int age in ages)
{
    if (!frequencies.ContainsKey(age))
    {
        frequencies[age] = 0;
    }
    frequencies[age] += 1;
}

// Find the age with the max frequency
int maxFreq = 0;
int modeAge = -1;
foreach (var entry in frequencies)
{
    if (entry.Value > maxFreq)
    {
        maxFreq = entry.Value;
        modeAge = entry.Key;
    }
}
Console.WriteLine("Max frequency: " + maxFreq); // Max frequency: 4
Console.WriteLine("Mode age: " + modeAge); // Mode age: 22

While loops can also be used similarly for complex tasks.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal