LINQ Basics
Filter with Where
LINQ extends collections with query operators.
var nums = new List<int> { 1, 2, 3, 4, 5 };
var evens = nums.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(",", evens));
Project with Select
Transform each element into a new shape.
var labels = nums.Select(n => $"#{n}");
foreach (var label in labels)
{
Console.WriteLine(label);
}
Pick a single item
FirstOrDefault returns a default when nothing matches.
int firstBig = nums.FirstOrDefault(n => n > 3);
Console.WriteLine(firstBig);
LINQ habits
- Queries are lazy until you enumerate or call
ToList - Keep lambdas short and readable
- Prefer LINQ for clarity, not for every tiny loop
- Method syntax is common; query syntax also exists
Comments
One comment per signed-in account. Comments are saved with this page’s URL.