Consider this C# code that counts elements in a list:
var numbers = new List<int> {1, 2, 3, 4, 5};
int count = numbers.Count(n => n > 3);
Console.WriteLine(count);What will be printed?
var numbers = new List<int> {1, 2, 3, 4, 5}; int count = numbers.Count(n => n > 3); Console.WriteLine(count);
Count counts how many items satisfy the condition.
Only numbers greater than 3 are 4 and 5, so count is 2.
Look at this code that sums numbers:
var values = new List<int> {10, 20, 30};
int total = values.Sum();
Console.WriteLine(total);What is printed?
var values = new List<int> {10, 20, 30}; int total = values.Sum(); Console.WriteLine(total);
Sum adds all numbers in the list.
10 + 20 + 30 equals 60.
Analyze this code that calculates average:
var scores = new List<double> {4.0, 5.0, 6.0};
double avg = scores.Average();
Console.WriteLine(avg);What will be printed?
var scores = new List<double> {4.0, 5.0, 6.0}; double avg = scores.Average(); Console.WriteLine(avg);
Average is total sum divided by count.
(4 + 5 + 6) / 3 = 15 / 3 = 5.
Consider this code:
var emptyList = new List<int>(); double avg = emptyList.Average(); Console.WriteLine(avg);
What happens when this runs?
var emptyList = new List<int>(); double avg = emptyList.Average(); Console.WriteLine(avg);
Average on empty collections throws an error.
Calling Average on an empty list throws InvalidOperationException because there is no element to average.
Given this code:
var data = new List<int> {1, 2, 3, 4, 5, 6};
int count = data.Count(n => n % 2 == 0 && n > 3);
Console.WriteLine(count);How many items satisfy the condition?
var data = new List<int> {1, 2, 3, 4, 5, 6}; int count = data.Count(n => n % 2 == 0 && n > 3); Console.WriteLine(count);
Count numbers that are even and greater than 3.
Numbers 4 and 6 are even and greater than 3, so count is 2.