Search⌘ K
AI Features

Common LINQ Operations

Learn to use common LINQ operations to query and manipulate collections in C#. Understand filtering with where clauses, sorting with orderby, projecting custom results, and combining multiple data sources. Explore both query syntax and method syntax to write efficient, readable code.

Most LINQ queries written using query syntax follow a predictable structure:

var result = from item in collection
select item;
The foundational structure of a LINQ query
  • Line 1: We define the data source (collection) and a range variable (item) that represents each individual element during iteration.

  • Line 2: We use the select statement to determine exactly what the query returns.

This basic syntax can be extended with filtering, sorting, projection, and other operations, which we explore individually.

Filter

To select items that match specific criteria, we use the where clause. After the where keyword, we provide a boolean expression that determines how the filtering occurs.

C# 14.0
using System.Collections.Generic;
using System.Linq;
var numbers = new List<int>()
{
1, 2, 3, 75, 43, 12, 99, 22, 76, 12, 874, 23
};
var evenNumbers = from number in numbers
where number % 2 == 0
select number;
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
  • Line 1: We import the System.Collections.Generic namespace to access the List<T> collection type.

  • Lines ...