LINQ

    Lesson 11 • Expert Track

    Query collections with clean, readable expressions — C#'s most powerful feature for working with data.

    What You'll Learn

    • • Filter data with Where and transform with Select
    • • Chain LINQ methods for complex queries
    • • Use aggregate methods: Sum, Average, Count, Min, Max
    • • Query objects with LINQ — sorting, filtering, projecting
    • • Choose between query syntax and method syntax

    Real-World Analogy

    LINQ is like having a personal assistant for your data. Instead of manually searching through a filing cabinet, you say "give me all invoices over £500, sorted by date." LINQ does the searching, filtering, and sorting for you in one clean sentence.

    Running C# Locally: Install the .NET SDK or use dotnetfiddle.net.

    Filtering & Transforming with LINQ

    LINQ (Language Integrated Query) adds SQL-like querying directly into C#. The two most important methods are Where (filter) and Select (transform). You chain them together using lambda expressions.

    LINQ Basics — Where, Select, Aggregates

    Filter, transform, and aggregate a list of numbers.

    Try it Yourself »
    C#
    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main()
        {
            List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
            // Where — filter elements
            var evens = numbers.Where(n => n % 2 == 0);
            Console.WriteLine("Even numbers: " + string.Join(", ", evens));
    
            // Select — transform elements
            var doubled = numbers.Select(n => n * 2);
            Console.WriteLine("Doubled: " + string.Join(", ", do
    ...

    Querying Objects

    LINQ truly shines when querying collections of objects. You can filter by properties, sort results, project into new shapes, and check conditions — all in a fluent, readable chain.

    LINQ with Objects — Students

    Query a list of students by GPA, age, and more.

    Try it Yourself »
    C#
    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public double GPA { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var students = new List<Student>
            {
                new Student { Name = "Alice", Age = 20, GPA = 3.8 },
                new Student { Name = "Bob", Age = 22, GPA = 3.2 },
                new Student { Name = "Charlie", Age = 19, GPA = 3.9 },
                new 
    ...

    Common Mistakes

    • Forgetting using System.Linq; — LINQ methods won't be available without this import.
    • Calling .First() on empty sequences — use .FirstOrDefault() to safely return null/default.
    • Multiple enumeration: Calling .ToList() forces evaluation. Without it, the query re-executes each time you iterate.

    Query Syntax vs Method Syntax

    C# offers two ways to write LINQ. Query syntax looks like SQL and can be more readable for joins and grouping. Method syntax uses extension methods and lambdas — it's more flexible and commonly used in production code.

    Query vs Method Syntax

    Compare both LINQ styles side by side.

    Try it Yourself »
    C#
    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    class Product
    {
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var products = new List<Product>
            {
                new Product { Name = "Laptop", Category = "Electronics", Price = 999m },
                new Product { Name = "Phone", Category = "Electronics", Price = 699m },
                new Product { Name 
    ...

    Pro Tips

    • 💡 LINQ is lazy — queries aren't executed until you iterate or call .ToList().
    • 💡 Use FirstOrDefault and SingleOrDefault to avoid exceptions on empty results.
    • 💡 Chain methods for readability: .Where().OrderBy().Select() reads like a sentence.
    • 💡 Method syntax is preferred in production code — it's more concise and composable.

    📋 Quick Reference

    MethodWhat It Does
    Where()Filter elements by condition
    Select()Transform / project elements
    OrderBy()Sort ascending
    First() / FirstOrDefault()Get first matching element
    Any() / All()Check if any/all match condition
    Sum() / Average() / Count()Aggregate calculations

    Lesson Complete! 🎉

    LINQ is a game-changer. Next up: writing non-blocking code with async and await.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service