How to Use the Where Method

Learn how to filter a collection with Where.

We'll cover the following

Now, let’s rewrite our example to find our favorite movies. We’ve decided a movie is a favorite if it has a rating greater than 4.5 points.

How to filter a collection with Where

To start using LINQ methods, let’s add the statement using System.Linq to our using declarations at the top of our file. Next, we want to filter our favorite movies, the ones with a rating greater than 4.5. The LINQ method Where filters and returns a new collection with all the elements that meet a condition.

Let’s replace the first foreach statement from our first example with the Where method. Then let’s keep the same IsFavorite() method to find if a movie has a rating that makes it a favorite film. Our example looks like this:

Get hands-on with 1000+ tech skills courses.