You can use LINQ on any collection, including lists of your own classes.
🏫 Example: Students
1
2
3
4
5
6
7
8
9
10
11
| class Student
{
public string Name;
public int Age;
}
var students = new List<Student>
{
new Student { Name = "Alice", Age = 20 },
new Student { Name = "Bob", Age = 18 },
new Student { Name = "Charlie", Age = 22 }
};
|
🔎 Filter Students by Age
1
2
3
| var adults = students.Where(s => s.Age >= 21);
foreach (var s in adults)
Console.WriteLine(s.Name);
|
🗂️ Sort and Select
1
2
3
4
| var names = students.OrderBy(s => s.Name)
.Select(s => s.Name.ToUpper());
foreach (var n in names)
Console.WriteLine(n);
|
💡 Try It!
Find the youngest student using LINQ:
1
2
| var youngest = students.OrderBy(s => s.Age).First();
Console.WriteLine(youngest.Name);
|
Next: Introduction to async programming!