LINQ Basics
LINQ (Language Integrated Query) queries collections declaratively with Where, Select, OrderBy, GroupBy — unified syntax for IEnumerable and IQueryable.
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.
flowchart LRSource[IEnumerable] --> Where[Where filter]Where --> Select[Select transform]Select --> Order[OrderBy]Order --> Result[ToList / First]
Step-by-step explanation
- Chain operators return IEnumerable without running yet.
- Terminal operator triggers enumeration.
- Multiple enumeration re-runs query — cache with ToList.
- Query syntax compiles to method calls.
- GroupBy produces IGrouping
. - Join matches outer/inner sequences on keys.
Practical code example
Filter active customers, project DTO, order by revenue:
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.CustomerSummarycarries 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?
Q2BeginnerSelect vs Where?
Q3IntermediateIEnumerable vs IQueryable?
Q4IntermediateFirst vs FirstOrDefault?
Q5AdvancedN+1 query problem with LINQ/EF?
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.