Using LINQ Where to Filter Data
LINQ
26 Articles
In this article, let's learn about how to use Where in LINQ in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ OrderBy to Sort Data in collections.
Table of Contents
Introduction
We can use LINQ Where to filter data within collections based on true or false condition(s). The resulting collection can be same, less or even empty. We can chain conditions with logical operators like &&, ||, !, etc. we're going to find out and use AND and OR in a where clause, and talk about building your own custom extension method.
TLDR
Where Single Property
The following example shows how to filter Product class by one property.
Code Sample - LINQ Where Single Property
Where Multiple Properties
The following example shows how to filter Product class with more than one property using AND, OR operators.
Code Sample - LINQ Where Multiple Properties
Custom Extension Method
Let's take a look at creating our own custom extension method where we create a method that returns an IEnumerable<T>, that way we can use this method on the query instead of like Where. For example. So we could do from prod in products select prod.ByColor, and then we pass in the parameter like Red. Now this is exactly like doing a where clause, but it allows us to do things that could be maybe more complicated. What we do is we create a static class that has a static method in it. And if you'll notice here, we're using the this keyword to key to the type of object, which in this case is an IEnumerable of Product, IEnumerable<T>, right? So if you're familiar with extension methods, this is a very common thing we do to extend classes that Microsoft has built or other people have built. We then also pass in any other parameters, in this case a color, and then we invoke the Where method to filter the data. So query, right, is what we passed in as the parameter, and we return query.Where, pass in product, product.Color is equal to the color that was passed in the parameter.
The following example shows how to filter Product class with custom extension method.
Code Sample - LINQ Where Custom Extension Method
Summary
In this article we learn't how to filter data within collection using LINQ. We also learn't how to filter with multiple fields using AND and OR conditions. We also made our own custom extension method to filter a collection. All these can be used with any IEnumerable or IQueryable types.