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!
Let's say we have a list of integers denoting the ages of a group of people:
C#1List<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:
C#1int numPeople = ages.Count; // Number of people (12) 2int totalAges = ages.Sum(); // Total age (276) 3int youngestAge = ages.Min(); // Youngest age (20) 4int oldestAge = ages.Max(); // Oldest age (27) 5 6// Use Sum and Count to find the average age 7double averageAge = (double)ages.Sum() / ages.Count; // Result: 23 8 9// Use Max() and Min() to find the range of ages 10int ageRange = ages.Max() - ages.Min(); // Result: 7
These functions provide essential aggregation operations and are widely used with data streams.
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:
C#1List<int> ages = new List<int>() { 21, 23, 20, 25, 22, 27, 24, 22, 25, 22, 23, 22 }; 2 3// Initialize a dictionary to store the frequency of each age 4Dictionary<int, int> frequencies = new Dictionary<int, int>(); 5 6// Use a for loop to populate frequencies 7foreach (int age in ages) 8{ 9 if (!frequencies.ContainsKey(age)) 10 { 11 frequencies[age] = 0; 12 } 13 frequencies[age] += 1; 14} 15 16// Find the age with the max frequency 17int maxFreq = 0; 18int modeAge = -1; 19foreach (var entry in frequencies) 20{ 21 if (entry.Value > maxFreq) 22 { 23 maxFreq = entry.Value; 24 modeAge = entry.Key; 25 } 26} 27Console.WriteLine("Max frequency: " + maxFreq); // Max frequency: 4 28Console.WriteLine("Mode age: " + modeAge); // Mode age: 22
While
loops can also be used similarly for complex tasks.
Finally, let's unwrap the Aggregate
method, a powerful tool for performing complex aggregations. It applies a binary function to all elements in an iterative and cumulative way. For example, let's calculate the product of all elements in a list using the Aggregate
method.
C#1List<int> ages = new List<int>() { 21, 23, 20, 25, 22 }; 2int product = ages.Aggregate(1, (a, b) => a * b); // 1 is the start value for the calculation 3// This performs the following calculation: (((((1 * 21) * 23) * 20) * 25) * 22) 4Console.WriteLine(product); // Output: 5313000
By using the multiplication function as the binary function, Aggregate
has computed the product of all elements in our list.
We can also use Aggregate
to accomplish more challenging tasks. Consider, for instance, the problem of separately computing the sums of even numbers and odd numbers in the ages
list.
C#1List<int> ages = new List<int>() { 21, 23, 20, 25, 22 }; 2var sums = ages.Aggregate(new { evens = 0, odds = 0 }, (acc, curr) => 3{ 4 if (curr % 2 == 0) 5 { 6 acc = new { evens = acc.evens + curr, odds = acc.odds }; 7 } 8 else 9 { 10 acc = new { evens = acc.evens, odds = acc.odds + curr }; 11 } 12 return acc; 13}); 14Console.WriteLine($"Evens sum: {sums.evens}, Odds sum: {sums.odds}"); // Output: Evens sum: 42, Odds sum: 69
In this second example, elements of the list are summed into even and odd categories. Starting with an accumulator object { evens: 0, odds: 0 }
, the function checks each element: if it's even, it adds to evens; if odd, it adds to odds. The final result is an object showing the sum of all even and odd numbers separately.
Fantastic! You've just learned how to use basic and advanced data aggregation methods in C#
, including using the Aggregate
method! These techniques are pivotal in data analysis and understanding. Now, get ready for the practical tasks lined up next. They'll reinforce the skills you've just gained. Remember, the more you practice, the better you become. Good luck with your practice!