LINQ (Language Integrated Query)
LINQ (Language Integrated Query) is a powerful C# feature that allows you to query collections using a SQL-like syntax directly in your C# code.
1 Query Syntax vs. Method Syntax
LINQ queries can be written in two ways:
- Query Syntax: Reads like SQL, starting with `from` and ending with `select`.
- Method Syntax: Uses extension methods and lambda expressions (`Where`, `Select`, `OrderBy`), which is more common and powerful in modern C#.
2 LINQ Code
Let's run a program filtering and sorting list collections using LINQ expressions:
C# — LINQ Queries
▶ Run Code
using System;
using System.Collections.Generic;
using System.Linq; // Required for LINQ extension methods
class Program {
static void Main() {
List<int> numbers = new List<int>() { 1, 4, 8, 12, 15, 20 };
// Filter numbers greater than 10 (using Method Syntax)
var filtered = numbers.Where(n => n > 10).ToList();
Console.Write("Numbers > 10: ");
foreach (var num in filtered) {
Console.Write(num + " ");
}
Console.WriteLine();
// Sort names alphabetically
List<string> names = new List<string>() { "Charlie", "Alice", "Bob" };
var sortedNames = names.OrderBy(name => name).ToList();
Console.WriteLine("Sorted Names: " + string.Join(", ", sortedNames));
}
}
3 Code Challenge
Challenge: Write a LINQ query that filters an array of test scores, returning only scores that are 80 or above, sorted in descending order. Output the filtered scores.