CodeBlanks Logo Icon CodeBlanks

Count and Sum

C# course · Intermediate · Lesson 95/116

Learn aggregate calculations with Count, Sum, Average, Min and Max.

Counting with Count

The Count method returns the number of elements in a collection. With a condition, it counts the matching elements: numbers.Count(n => n > 5). The result is an int.

Tip: for a simple empty check, prefer !Any() over Count() == 0. Count walks every element; Any stops at the first. Still, when you need a conditional count, Count(condition) is the right tool.

Sum, Average, Min, Max

For numeric collections there are four aggregate methods: Sum total, Average mean, Min smallest, Max largest. For new[] { 3, 7, 2 } we get Sum() = 12, Average() = 4, Min() = 2, Max() = 7.

They accept a selector: students.Sum(s => s.Grade) totals the grades. On an empty collection Sum returns 0; Average, Min and Max throw. So check with Any() first when the collection may be empty.

Exercise Print sum and average

Compute Sum() and Average() of the numbers array and print them with Console.WriteLine. You do not need to cast the average to int.

Show example solution
Add Console.WriteLine(numbers.Sum()); and Console.WriteLine(numbers.Average());.
Example solution:
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 4, 8, 12 };
        Console.WriteLine(numbers.Sum());
        Console.WriteLine(numbers.Average());
    }
}

Test yourself

  1. Complete the Count call

    int count = numbers.____(n => n % 2 == 0);
    Show answer
    int count = numbers.Count(n => n % 2 == 0);
  2. Which one gives the average?

    new[] { 4, 8, 12 }
    • Sum()
    • Min()
    • Average()
    • Count()
    Show answer

    Average() — Correct. Average() gives the mean; in the example (4+8+12)/3 = 8.

  3. Match each method to its result

    Sum()
    Total
    Average()
    Mean
    Min()
    Smallest
    Max()
    Largest

All lessons in Intermediate