The where
operator in LINQ (Language-Integrated Query) filters a series of data depending on the given criteria. It enables us to pick only those components from a collection that meet specific criteria. In LINQ queries, the where
operator is frequently used to limit the results to those that satisfy particular requirements.
We can use the where
operator in two ways:
Using where
with select
Using the extension method
where
operator with the select
operatorThe simple way to use the where
operator is to use it with the combination of the select
operator, which is explained below:
Here’s the basic syntax to use the where
operator:
var result = from item in collectionwhere conditionselect item;
Here, collection
is the source collection (e.g., a list, array, or any IEnumerable). A boolean statement called condition
defines the filtering requirements. The result will only be comprised of items for which this condition evaluates to true.
Let’s demonstrate the use of where
in combination with the select
operator with the following example:
using System;using System.Linq;using System.Collections.Generic;class Test{static void Main(string[] args){List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };var evenNumbers = from num in numberswhere num % 2 == 0select num;Console.WriteLine("Even values are");foreach (var n in evenNumbers){Console.WriteLine(n);}}}
Lines 1–3: It imports the necessary namespaces for using system-related classes, LINQ, and generic collections.
Line 9: It creates a list of integers called numbers
and initializes it with 10 numbers.
Lines 11–13: These create a new collection called evenNumbers
by selecting and storing only the even numbers from the numbers
list using a LINQ query. The where
clause filters numbers based on the condition num % 2 == 0
, ensuring only even values are included.
Lines 16–19: These iterate through the evenNumbers
collection and prints each even number to the console.
We can also use the Where
operator using the
Here’s the basic syntax to use Where
operator using the extension method:
var result = collection.Where(item => condition);
Here, collection
is the source collection (e.g., a list, array, or any IEnumerable). A boolean statement called condition
defines the filtering requirements. The result will only be comprised of items for which this condition evaluates to true.
Let’s demonstrate its usage:
using System;using System.Linq;using System.Collections.Generic;class Test{static void Main(string[] args){List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };var evenNumbers = numbers.Where(num => num % 2 == 0);Console.WriteLine("Even values are");foreach (var n in evenNumbers){Console.WriteLine(n);}}}
Line 11: It creates a new collection called evenNumbers
by selecting and storing only the even numbers from the numbers
list using a LINQ extension method. The lambda expression num => num % 2 == 0
is the condition that filters for even values.
Free Resources