One of the main task of a Linq query is to filter the results from a larger collection on some criteria. This is perform by Where operator, which tests each element within a source collection and returns only those elements that pass when tested against a given predicate expression.
A predicate is simply an expression that takes an element of the items in source collection and returns true or false.
The extension method for the Where operator is very simple; it iterates the source collection using a foreach loop, testing each element and return passed elements. Here is the actual code in the System.Linq library:
Where Filter Using a Lambda Expression
When constructing a predicate for the Where operator, the predicates takes an input of the type elements in source collection and return a Boolean value (true or false). For example:
In this code, each string value from the animals array is passed to the Where extension method in a range variable called a. Each string in a is evaluated against the predicate function, and only those strings that
pass (return true) are returned in the query results. For this example, only two strings pass the test and are written to the console window.
Where Filter Query Expressions
The query expression where clause syntax eliminates the explicit range variable definition and lambdas exression operator(=>), and makes it more readable and more familiar to SQL-style clause.
Using an External Method for Filtering
Suppose if the Predicate is lengthy and might be used in more than one query expression, we should consider putting it in its own method, then we don’t have to write predicate in inline queries.
Filtering by Index Position
Linq query opearators expose a variation as it gives the index position of each collection elements. The zero-based index position can be passed into a lambda expression predicate by assigning a variable name as the second argument (after the element range variable).
But it have limitations also:
- To access the index position, a lambda expression must be used,
- This can only be achieved using the extension method syntax.
In this post I discussed various method for Where operator of Linq.
Please leave a comment, it encourage me to write quality articles.
Happy reading and Coding 🙂