LINQ (Language Integrated Query) allows you to write queries directly in C# to filter, sort, and transform collections. LINQ works with arrays, lists, XML, databases, and any IEnumerable source.
C#
Beginner
12 min read
LINQ in C#
Example
using System;
using System.Collections.Generic;
using System.Linq;
var students = new List<Student> {
new("Alice", 92, "Math"),
new("Bob", 78, "Science"),
new("Carol", 95, "Math"),
new("Dave", 85, "Science"),
new("Eve", 70, "Math"),
};
// Filter + sort
var topMath = students
.Where(s => s.Subject == "Math" && s.Grade >= 90)
.OrderByDescending(s => s.Grade)
.Select(s => new { s.Name, s.Grade });
foreach (var s in topMath)
Console.WriteLine($"{s.Name}: {s.Grade}");
// Grouping
var bySubject = students.GroupBy(s => s.Subject);
foreach (var group in bySubject) {
double avg = group.Average(s => s.Grade);
Console.WriteLine($"{group.Key} avg: {avg:F1}");
}
record Student(string Name, int Grade, string Subject);