C# Programming Tutorial 0/45 lessons ~6 min read Lesson 26

    LINQ Basics

    LINQ (Language Integrated Query) queries collections declaratively with Where, Select, OrderBy, GroupBy — unified syntax for IEnumerable and IQueryable.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    LINQ (Language Integrated Query) queries collections declaratively with Where, Select, OrderBy, GroupBy — unified syntax for IEnumerable and IQueryable. It powers EF Core database queries and in-memory transforms alike.

    Method syntax vs query syntax — interviews accept both; method syntax more common in production. Deferred execution means chaining builds expression tree until enumeration.

    The story

    A sales manager asks for the top five active customers ranked by revenue this quarter. Instead of writing manual loops and sort logic, the analytics service chains LINQ operators — filter active accounts, sort by revenue descending, take five, and project to a summary DTO for the dashboard API.

    Understanding the topic

    Key concepts

    • Extension methods on IEnumerable.
    • Lambda predicates: x => x.Age > 18.
    • Deferred execution until foreach/ToList.
    • Select projects; Where filters; OrderBy sorts.
    • First, Single, Any, Count terminal operators.
    • IQueryable translates to SQL via EF provider.
    text
    flowchart LR
    Source[IEnumerable] --> Where[Where filter]
    Where --> Select[Select transform]
    Select --> Order[OrderBy]
    Order --> Result[ToList / First]

    Step-by-step explanation

    1. Chain operators return IEnumerable without running yet.
    2. Terminal operator triggers enumeration.
    3. Multiple enumeration re-runs query — cache with ToList.
    4. Query syntax compiles to method calls.
    5. GroupBy produces IGrouping.
    6. Join matches outer/inner sequences on keys.

    Practical code example

    Filter active customers, project DTO, order by revenue:

    csharp
    namespace TechLearningPro.LinqBasics;
    public record Customer(Guid Id, string Name, bool IsActive, decimal Revenue);
    public static class CustomerQueries
    {
    public static List<CustomerSummary> TopActiveCustomers(IEnumerable<Customer> customers, int n) =>
    customers
    .Where(c => c.IsActive)
    .OrderByDescending(c => c.Revenue)
    .Take(n)
    .Select(c => new CustomerSummary(c.Id, c.Name, c.Revenue))
    .ToList();
    }
    public sealed record CustomerSummary(Guid Id, string Name, decimal Revenue);

    Line-by-line code explanation

    • record Customer(Guid Id, string Name, bool IsActive, decimal Revenue) is the source data shape.
    • TopActiveCustomers(IEnumerable<Customer> customers, int n) accepts any enumerable source — list, array, or EF query.
    • .Where(c => c.IsActive) keeps only active customers in the pipeline.
    • .OrderByDescending(c => c.Revenue) sorts by revenue highest-first.
    • .Take(n) limits results to the requested top N count.
    • .Select(c => new CustomerSummary(...)) projects to a lighter DTO for the API response.
    • .ToList() materializes the deferred query into a concrete list — execution happens here.
    • CustomerSummary carries only the fields the dashboard needs, not the full entity.

    Key takeaway: Method syntax pipeline reads top-to-bottom. ToList materializes once. Same filters on IQueryable become SQL WHERE/ORDER BY/TOP.

    Real-world use

    Where you'll use this in production

    • Reporting queries over in-memory collections.
    • EF Core database filtering without raw SQL.
    • API pagination with Skip/Take.
    • Excel export row projection.

    Best practices

    • Materialize once if enumerating multiple times.
    • Push filters to IQueryable before ToList for SQL efficiency.
    • Avoid First when Any suffices for existence check.
    • Use FirstOrDefault not First when missing ok.
    • Name lambdas clearly for complex queries — extract method.

    Common mistakes

    • Multiple enumeration hitting DB repeatedly.
    • Filtering after ToList pulled entire table.
    • First on empty — InvalidOperationException.
    • Capturing mutable outer variable unexpectedly in closure.

    Advanced interview questions

    Q1BeginnerWhat is deferred execution?
    LINQ builds pipeline; runs on enumeration.
    Q2BeginnerSelect vs Where?
    Where filters; Select transforms/projects.
    Q3IntermediateIEnumerable vs IQueryable?
    IEnumerable in-memory; IQueryable expression tree translatable to SQL.
    Q4IntermediateFirst vs FirstOrDefault?
    First throws if empty; FirstOrDefault returns default.
    Q5AdvancedN+1 query problem with LINQ/EF?
    Loading related entities in loop — fix with Include, projection, or split query.

    Summary

    LINQ queries collections with composable operators. Deferred execution — materialize consciously with ToList. Same patterns work in-memory and via EF Core IQueryable. Master Where, Select, OrderBy, GroupBy, Join. Next: advanced LINQ — grouping, joins, aggregates.

    Ready to mark this lesson complete?Track your journey across the entire course.