LINQ Basics
Count and Sum
LINQ has aggregate methods for counting and adding values.
aggregate
An aggregate method combines a sequence into one result.
Count and Sum
CountSum.cs
Replay: real traced execution (multi-file project)
using System;
using System.Linq;
class Program
{
static void Main()
{
int passing = 70;
int[] scores = { 55, 72, 90 };
int passed = scores.Count(score => score >= passing);
int total = scores.Sum();
Console.WriteLine($"passing={passing}");
Console.WriteLine($"passed={passed}");
Console.WriteLine($"total={total}");
}
}
using System;
using System.Linq;
class Program
{
static void Main()
{
int passing = 60;
int[] scores = { 55, 72, 90 };
int passed = scores.Count(score => score >= passing);
int total = scores.Sum();
Console.WriteLine($"passing={passing}");
Console.WriteLine($"passed={passed}");
Console.WriteLine($"total={total}");
}
}
using System;
using System.Linq;
class Program
{
static void Main()
{
int passing = 85;
int[] scores = { 55, 72, 90 };
int passed = scores.Count(score => score >= passing);
int total = scores.Sum();
Console.WriteLine($"passing={passing}");
Console.WriteLine($"passed={passed}");
Console.WriteLine($"total={total}");
}
}
passing ← 70, passed ← 2, total ← 217
5{6 static void Main()7 {8 int passing→ 70 = 70; //@passing=60, 859 int[] scores = { 55, 72, 90 };10 int passed→ 2 = scores.Count(score => score >= passing);11 int total→ 217 = scores.Sum();1213 Console.WriteLine($"passing={passing70}");14 Console.WriteLine($"passed={passed2}");15 Console.WriteLine($"total={total217}");16 }outputpassing=70 passed=2 total=217
passing ← 60, passed ← 2, total ← 217
5{6 static void Main()7 {8 int passing→ 60 = 60;9 int[] scores = { 55, 72, 90 };10 int passed→ 2 = scores.Count(score => score >= passing);11 int total→ 217 = scores.Sum();1213 Console.WriteLine($"passing={passing60}");14 Console.WriteLine($"passed={passed2}");15 Console.WriteLine($"total={total217}");16 }outputpassing=60 passed=2 total=217
passing ← 85, passed ← 1, total ← 217
5{6 static void Main()7 {8 int passing→ 85 = 85;9 int[] scores = { 55, 72, 90 };10 int passed→ 1 = scores.Count(score => score >= passing);11 int total→ 217 = scores.Sum();1213 Console.WriteLine($"passing={passing85}");14 Console.WriteLine($"passed={passed1}");15 Console.WriteLine($"total={total217}");16 }outputpassing=85 passed=1 total=217