C# · Intermediate

LINQ

LINQ (Language-Integrated Query) lets you filter, sort, group and transform collections with concise, readable C#.

Advanced 5 min Lesson 21 of 26Examples target C# 13 on .NET 9 unless stated otherwise.
0/26 in C#
On this page · 5 min · Advanced

In simple words#

LINQ is like using filters on a shopping app: “show phones, under ₹20,000, sorted by rating”. You describe what you want; LINQ finds it in your list or database.

LINQ
Language Integrated Query — query data in C#.
Where / Select / OrderBy
Filter, transform, sort.
Deferred execution
The query runs only when you use the results.

Learning objectives#

  • Filter and project with Where and Select
  • Sort and group data
  • Pick single elements safely
  • Understand deferred execution

Explanation#

LINQ methods are extension methods on IEnumerable<T>. Each takes a lambda that describes what to do with each element.

Most LINQ operators use deferred execution: building the query does nothing until you enumerate it with foreach, ToList(), Count() and so on.

With Entity Framework Core, the same operators on IQueryable<T> are translated into SQL and run in the database.

Code example: Querying students#

C#Program.cs Illustrative
var students = new List<Student>
{
    new("Asha", "React", 91),
    new("Ravi", "Angular", 78),
    new("Meera", "React", 85),
    new("Kabir", "Angular", 64),
};


var topReact = students
    .Where(s => s.Course == "React" && s.Score >= 80)
    .OrderByDescending(s => s.Score)
    .Select(s => s.Name)
    .ToList();


Console.WriteLine(string.Join(", ", topReact));


foreach (var group in students.GroupBy(s => s.Course))
{
    Console.WriteLine(
quot;
{group.Key}: avg {group.Average(s => s.Score):F1}");
} var first = students.FirstOrDefault(s => s.Score > 95); Console.WriteLine(first?.Name ?? "No one above 95"); record Student(string Name, string Course, int Score);
Expected output
Asha, Meera
React: avg 88.0
Angular: avg 71.0
No one above 95

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. Where keeps React students scoring at least 80.
  2. OrderByDescending sorts by score; Select projects each student to just the name.
  3. ToList() executes the query and stores the result.
  4. GroupBy creates one group per course; Average computes the mean score per group.
  5. FirstOrDefault returns null when nothing matches instead of throwing.

Real-world use case#

Filtering products in an e-commerce API, building report summaries, and writing EF Core queries in ASP.NET Core controllers.

Common mistakes#

Enumerating a query many times

Each enumeration re-runs a deferred query (and with EF Core, re-queries the database). Call ToList() once if you need the results repeatedly.

First() on possibly empty data

First() throws InvalidOperationException if nothing matches. Use FirstOrDefault() and handle null.

Best practices#

  • Use method syntax consistently in a codebase
  • Materialise with ToList() when results are reused
  • With EF Core, filter before ToList() so filtering happens in SQL
  • Use Any() instead of Count() > 0

Remember this#

Where = filter. Select = transform. OrderBy = sort.

Nothing runs until you enumerate (foreach, ToList, Count).

First throws when empty; FirstOrDefault returns null.

Practice exercise#

Your task: Return the names of all Angular students in alphabetical order.

Need a hint?
Chain Where (course is Angular), OrderBy (name) and Select (name).
Show solution
C# Illustrative
var angular = students
    .Where(s => s.Course == "Angular")
    .OrderBy(s => s.Name)
    .Select(s => s.Name);

Mini quiz#

LINQ quizMultiple choice Question 1 of 3

When does a LINQ Where(...) query actually run?

Score so far: 0/0

Want more? Practise all C# MCQs · C# interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.