Linq’s Where Clause (operator) : Result Filtering

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.

Introduction

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.
For example:

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.
For example:

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:

  1. To access the index position, a lambda expression must be used,
  2. This can only be achieved using the extension method syntax.

For example:

Summary

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 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s