C#
Beginner
1 min read
LINQ Basics: Where, Select, and ToList
Example
// LINQ fundamentals: Where, Select, OrderBy, ToList
var products = new List<(string Name, string Category, decimal Price, int Stock)>
{
("Laptop", "Electronics", 999.99m, 10),
("Phone", "Electronics", 699.99m, 5),
("Desk", "Furniture", 349.99m, 20),
("Chair", "Furniture", 199.99m, 15),
("Keyboard", "Electronics", 79.99m, 50),
("Monitor", "Electronics", 399.99m, 8),
};
// Where — filter
var electronics = products
.Where(p => p.Category == "Electronics")
.ToList();
Console.WriteLine($"Electronics count: {electronics.Count}"); // 4
// Select — project to a new shape
var names = products.Select(p => p.Name).ToList();
Console.WriteLine(string.Join(", ", names));
// Select with anonymous type
var summaries = products
.Where(p => p.Price > 300)
.Select(p => new { p.Name, p.Price, p.Category })
.OrderBy(p => p.Price)
.ToList();
foreach (var s in summaries)
Console.WriteLine($"{s.Name,-12} {s.Category,-12} ${s.Price:F2}");
// Method chaining — filter, project, sort, take
var top3Cheap = products
.Where(p => p.Stock > 0)
.OrderBy(p => p.Price)
.Take(3)
.Select(p => $"{p.Name} (${p.Price:F2})")
.ToList();
Console.WriteLine("Top 3 cheapest:");
top3Cheap.ForEach(Console.WriteLine);
// Aggregate operators
decimal totalValue = products.Sum(p => p.Price * p.Stock);
Console.WriteLine($"Total inventory value: ${totalValue:N2}");