2.4.10 Using the Count Property of a List

Using the Count Property of a List

The coach calculates average goals per recorded round. Count supplies the number of scores, while a loop supplies their total.

Explore the idea
Read the current number of items
Calculate an average safely

Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method.

Average goals per round
List<int> roundGoals = new List<int>();
roundGoals.Add(2);
roundGoals.Add(0);
roundGoals.Add(3);
double totalGoals = 0;

foreach (int goals in roundGoals)
{
    totalGoals = totalGoals + goals;
}

double averageGoals = 0;
bool hasAverage = false;

if (roundGoals.Count > 0)
{
    averageGoals = totalGoals / roundGoals.Count;
    hasAverage = true;
}

The total progresses from 0 to 2, remains 2, then becomes 5. Count is 3, so averageGoals is approximately 1.67. The zero-score round belongs in the denominator because the question asks about all recorded rounds.

Handle an empty list
Different inputs
Scores Count Total Average result
2, 0, 3 3 5 About 1.67; hasAverage true
0, 0 2 0 0; hasAverage true
No scores 0 0 No average; hasAverage false
Trace the worked example
Average calculation totals all scores, divides only when Count is positive, and sets hasAverage only when an average is calculated.
Total the scores, then guard the average calculation
  • New
  • Changed
  • Removed
Predict and check