SyntaxStudy
Sign Up
C# LINQ Basics: Where, Select, and ToList
C# Beginner 1 min read

LINQ Basics: Where, Select, and ToList

Language Integrated Query (LINQ) is a set of extension methods on `IEnumerable` that provide a consistent, composable API for filtering, transforming, and aggregating sequences. Queries are lazily evaluated: the pipeline is not executed until you iterate over the result or call a materialising operator like `ToList()` or `Count()`. `Where` filters a sequence based on a predicate. `Select` projects each element to a new form. These two operators, combined with `ToList`, cover the majority of everyday data manipulation tasks. Lambda expressions (`=>`) provide concise inline functions that LINQ operators accept as arguments. LINQ also supports a query expression syntax that resembles SQL. Under the hood it compiles to the same method calls. Most C# developers prefer the method syntax for its composability, but query syntax can be more readable for complex join and group operations.
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}");