C# ยท Chapter 43 of 46

C# LINQ Basics

LINQ (Language Integrated Query) lets you query and transform collections, like arrays and lists, using a clean, expressive syntax directly in C#. It's part of the System.Linq namespace.

LINQ methods like Where(), Select(), and OrderBy() let you filter, transform, and sort data without writing manual loops, making code shorter and more readable.

Syntax
collection.Where(x => condition);
collection.Select(x => transform);

Filtering with Where

Where() filters a collection based on a condition, returning only the elements that satisfy it. It uses a lambda expression, like `x => x > 5`, to define the condition.

Transforming and sorting

Select() transforms each element into a new form, and OrderBy()/OrderByDescending() sort a collection. These methods can be chained together for powerful queries.

Example 1 (csharp)
using System;
using System.Linq;

class Program {
  static void Main() {
    int[] numbers = { 1, 2, 3, 4, 5, 6 };
    var evens = numbers.Where(n => n % 2 == 0);
    Console.WriteLine(string.Join(", ", evens));
  }
}
Output
2, 4, 6

Where() filters the array, keeping only the even numbers.

Example 2 (csharp)
using System;
using System.Linq;

class Program {
  static void Main() {
    int[] numbers = { 1, 2, 3 };
    var squared = numbers.Select(n => n * n);
    Console.WriteLine(string.Join(", ", squared));
  }
}
Output
1, 4, 9

Select() transforms each number into its square.

Key points

  • LINQ requires `using System.Linq;`.
  • Where() filters elements based on a condition.
  • Select() transforms each element into a new form.
  • LINQ methods use lambda expressions like `x => x > 5`.
๐Ÿ’ก Note: LINQ works on any collection implementing IEnumerable<T>, including arrays, lists, and dictionaries.

๐Ÿ“ Quick Quiz

1. Which LINQ method filters a collection based on a condition?

2. Which namespace must be imported to use LINQ?

3. What does Select() do?