← Back to C# Course | Chapter 9: Collections | Lesson 6 of 7

LINQ Basics

LINQ lets you ask questions about a collection in a short, readable way, like 'show me only the red ones sorted by size'. It filters, sorts, and summarizes lists for you.

In this page:

  1. LINQ Basics
Syntax
csharp
using System.Linq;

var result = collection
    .Where(item => condition)
    .Select(item => expression)
    .ToList();

LINQ Basics

LINQ (Language Integrated Query) lets you filter, transform, and aggregate collections declaratively using methods like Where, Select, and OrderBy.

It's part of System.Linq and works over any IEnumerable<T>. LINQ queries are typically chained together to express data pipelines in a single readable statement.

Note: LINQ methods are lazily evaluated — they don't run until you enumerate the result, e.g. with foreach or .ToList().

Example: LINQ Basics

markup
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };

        var evenSquares = numbers
            .Where(n => n % 2 == 0)
            .Select(n => n * n)
            .ToList();

        foreach (int n in evenSquares)
        {
            Console.WriteLine(n);
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting that many LINQ queries run lazily, so the result is computed only when you enumerate it.
  2. Forgetting using System.Linq; and getting a missing method error.
  3. Calling First() on an empty sequence, which throws; use FirstOrDefault().
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.