Group Students with LINQ
Group records and calculate category averages.
Introduction
GroupBy turns a sequence into keyed groups that can be aggregated independently.
Each grouping exposes its Key and can be queried with the normal LINQ aggregate operators.
Runnable C# example
Program.cs
using System;
using System.Linq;
record Student(string Name, string Grade, int Score);
class Program
{
static void Main()
{
var students = new[] { new Student("Ada", "A", 95), new Student("Lin", "B", 84), new Student("Grace", "A", 91) };
foreach (var group in students.GroupBy(s => s.Grade).OrderBy(g => g.Key))
Console.WriteLine($"{group.Key}: {group.Average(s => s.Score):F1}");
}
}
A: 93.0
B: 84.0Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges