Filtering and Ordering Operations

Learn the basics of filtering and ordering query operations in LINQ.

We'll cover the following...

Overview

In this lesson, we’ll learn how to filter and order queries in LINQ using query syntax and query methods.

Filtering

Filtering refers to restricting a result set to only those elements that satisfy a specified condition. The illustration below shows the results of filtering a sequence of characters. The predicate for the filtering operation specifies that the character must be an “A.”

We’ll demonstrate filtering operations using the C# console app project below:

{
    "version": "0.2.0",
    "configurations": [
        {
            // Use IntelliSense to find out which attributes exist for C# debugging
            // Use hover for the description of the existing attributes
            // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            // If you have changed target frameworks, make sure to update the program path.
            "program": "${workspaceFolder}/bin/Debug/net6.0/QueryData.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
            "console": "internalConsole",
            "stopAtEntry": false
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}
Filtering an array of letters using LINQ query syntax

Click the “Run” button above, and execute the command below in the terminal:

dotnet run

Below is a snippet of the output:

A A

With query syntax, we filter results by applying conditions using a where clause.

Note the following:

  • Lines 4–6 of Program.cs highlight a ...