What is the use of "Where" operator in LINQ?
The Where
operator in LINQ is used to filter a sequence (collection) based on a specified condition. It allows you to extract elements from a sequence that satisfy a given predicate or condition.
Here's the syntax of the Where
operator in LINQ:
IEnumerable<TSource> result = sequence.Where(predicate);
-
sequence
represents the collection or sequence of elements from which you want to filter.
-
predicate
is a lambda expression or delegate that defines the condition for filtering the elements.
Example:
int[] numbers = { 1, 2, 3, 4, 5 };
IEnumerable<int> evenNumbers = numbers.Where(num => num % 2 == 0);
In this example, the Where
operator is used to filter the numbers
array and retrieve only the even numbers. The operator takes a lambda expression num => num % 2 == 0
as a parameter, which defines the condition for selecting the elements. The resulting evenNumbers
variable will contain the sequence {2, 4}.
The Where
operator has the following characteristics:
-
It applies the specified condition to each element in the sequence and returns a new sequence that includes only the elements that satisfy the condition.
- The condition is defined using a lambda expression or delegate that takes an element as input and returns a Boolean value indicating whether the element should be included in the result.
- The result of the
Where
operator is an IEnumerable<TSource>
that represents the filtered sequence.
The Where
operator is useful when you want to extract elements from a sequence based on a specific condition. It allows you to perform powerful filtering operations on collections, selecting only the elements that meet the desired criteria.