Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Aggregate functions (Count, Sum, Average) in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Aggregate functions (Count, Sum, Average)
Start with a list of numbers
Apply Count function
Get total number of items
Apply Sum function
Add all numbers together
Apply Average function
Divide Sum by Count
Result output
This flow shows how we start with a list, count items, sum them, then find the average by dividing sum by count.
Execution Sample
C Sharp (C#)
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = {2, 4, 6, 8};
        int count = numbers.Count();
        int sum = numbers.Sum();
        double average = numbers.Average();
        Console.WriteLine($"Count: {count}, Sum: {sum}, Average: {average}");
    }
}
This code counts, sums, and averages the numbers in the array, then prints the results.
Execution Table
StepActionValue/ResultExplanation
1Initialize array[2, 4, 6, 8]Numbers list created
2Count()4There are 4 numbers in the list
3Sum()20Sum of 2+4+6+8 equals 20
4Average()5.0Average is sum (20) divided by count (4)
5Print outputCount: 4, Sum: 20, Average: 5Final output displayed
💡 All aggregate functions applied and output printed
Variable Tracker
VariableStartAfter CountAfter SumAfter AverageFinal
numbers[2,4,6,8][2,4,6,8][2,4,6,8][2,4,6,8][2,4,6,8]
countundefined4444
sumundefinedundefined202020
averageundefinedundefinedundefined5.05.0
Key Moments - 3 Insights
Why does Average() return a double instead of an int?
Average() divides sum by count, which can result in a decimal number. So it returns a double to keep the decimal part, as shown in step 4 of the execution_table.
Does Count() count the sum of numbers or the number of items?
Count() returns the number of items in the list, not their sum. Step 2 in the execution_table shows Count() returns 4, the number of elements.
Can Sum() be used on an empty list?
Yes, Sum() on an empty list returns 0. But Average() on an empty list throws an error because it divides by zero.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'sum' after step 3?
A4
B5.0
C20
DUndefined
💡 Hint
Check the 'Value/Result' column for step 3 in execution_table
At which step does the program calculate the average?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look for the step where Average() is called in execution_table
If the array was empty, what would Count() return?
A0
BError
CNull
D1
💡 Hint
Count() returns the number of items, so empty means zero items
Concept Snapshot
Aggregate functions in C#:
- Count() returns number of items
- Sum() adds all items
- Average() divides sum by count
- Average() returns double for decimals
- Use on collections like arrays or lists
Full Transcript
This example shows how to use aggregate functions Count, Sum, and Average in C#. We start with an array of numbers. Count() tells us how many numbers are in the array. Sum() adds all the numbers together. Average() divides the sum by the count to find the average value. The code prints all three results. Average returns a double because the result can have decimals. Count returns the number of items, not their sum. Sum returns zero if the list is empty, but Average will cause an error if the list is empty because it divides by zero.

Practice

(1/5)
1.

Which aggregate function in C# is used to find how many items are in a list?

easy
A. Count
B. Sum
C. Average
D. Max

Solution

  1. Step 1: Understand the purpose of Count

    The Count function returns the number of elements in a collection.
  2. Step 2: Compare with other aggregate functions

    Sum adds values, Average calculates mean, Max finds the largest value, so they do not count items.
  3. Final Answer:

    Count -> Option A
  4. Quick Check:

    Count = number of items [OK]
Hint: Count counts items, Sum adds, Average finds mean [OK]
Common Mistakes:
  • Confusing Sum with Count
  • Using Average to count items
  • Thinking Max counts items
2.

Which of the following is the correct syntax to calculate the sum of integers in a list named numbers?

var total = ???;
easy
A. numbers.Sum()
B. numbers.Count()
C. Sum(numbers)
D. numbers.Average()

Solution

  1. Step 1: Identify the method to sum list elements

    The Sum() method is called on the list to add all elements.
  2. Step 2: Check syntax correctness

    numbers.Sum() is the correct syntax; Count() counts items, Average() finds mean, Sum(numbers) is invalid.
  3. Final Answer:

    numbers.Sum() -> Option A
  4. Quick Check:

    Sum() adds list values [OK]
Hint: Use list.Sum() to add all numbers [OK]
Common Mistakes:
  • Using Count() instead of Sum()
  • Calling Sum as a standalone function
  • Using Average() to sum values
3.

What is the output of this C# code?

var numbers = new List<int> { 2, 4, 6, 8 };
var result = numbers.Average();
Console.WriteLine(result);
medium
A. 20
B. 6
C. 4
D. 5

Solution

  1. Step 1: Calculate the sum of the list elements

    Sum = 2 + 4 + 6 + 8 = 20
  2. Step 2: Calculate the average

    Average = Sum / Count = 20 / 4 = 5.0
  3. Step 3: Check the output type

    Average returns a double, so output is 5 (printed as 5)
  4. Final Answer:

    5 -> Option D
  5. Quick Check:

    Average = 20 / 4 = 5 [OK]
Hint: Average = sum of values divided by count [OK]
Common Mistakes:
  • Adding values but not dividing by count
  • Confusing sum with average
  • Miscounting number of elements
4.

Identify the error in this code snippet and choose the correct fix:

var numbers = new int[] { 1, 2, 3 };
var total = numbers.Count + 5;
Console.WriteLine(total);
medium
A. No error, code is correct
B. Replace Count with Sum()
C. Replace Count with Count()
D. Replace Count with Average()

Solution

  1. Step 1: Identify the error in Count usage

    Count is a method, so it requires parentheses: Count()
  2. Step 2: Fix the syntax

    Change numbers.Count to numbers.Count() to get the number of elements.
  3. Final Answer:

    Replace Count with Count() -> Option C
  4. Quick Check:

    Count() is a method, not a property [OK]
Hint: Count is a method, always use parentheses [OK]
Common Mistakes:
  • Using Count without parentheses
  • Replacing Count with Sum or Average incorrectly
  • Assuming Count is a property
5.

You have a list of exam scores: var scores = new List<int> { 70, 85, 90, 100, 65 };. You want to find the average score but only for scores above 80. Which code snippet correctly calculates this?

hard
A. var avg = scores.Average(s => s > 80);
B. var avg = scores.Where(s => s > 80).Average();
C. var avg = scores.Sum(s => s > 80) / scores.Count();
D. var avg = scores.Count(s => s > 80) / scores.Sum();

Solution

  1. Step 1: Filter scores greater than 80

    Use Where(s => s > 80) to select only scores above 80.
  2. Step 2: Calculate average of filtered scores

    Call Average() on the filtered list to get the mean of those scores.
  3. Final Answer:

    var avg = scores.Where(s => s > 80).Average(); -> Option B
  4. Quick Check:

    Filter then average = correct approach [OK]
Hint: Filter with Where(), then call Average() [OK]
Common Mistakes:
  • Passing condition directly to Average()
  • Dividing sum by total count instead of filtered count
  • Using Count divided by Sum incorrectly