Using LINQ Where to Filter Data
In this post I will teach you how to filter data within collections using LINQ in .NET. All with live working demo.

On this page
What you'll learn
This article explains how to use the Where method in LINQ to filter data in .NET.
Note: If you haven't already, read the article on Using LINQ OrderBy to Sort Data in collections.

Why it matters
The Where method in LINQ allows filtering collections based on conditions. The resulting collection can be the same, smaller, or even empty. You can chain conditions using logical operators like &&, ||, and !.
Implementation
Filtering by Single Property
Example of filtering a Product class by a single property.
List<Product> products = GetProducts();
//Method Syntax
List<Product> filterProducts = products
.Where(product => product.Shape == "Diamond")
ToList();
//Query Syntax
List<Product> filterProducts = (from product in products
where product.Name == "Diamond")
.ToList();
Filtering by Multiple Properties
Example of filtering a Product class by multiple properties using AND and OR operators.
List<Product> products = GetProducts();
//Method Syntax
List<Product> filterProducts = products
.Where(product => product.Shape == "Diamond" || product.Color == "Red")
ToList();
//Query Syntax
List<Product> filterProducts = (from product in products
where product.Name == "Diamond" || product.Color == "Red")
.ToList();
Custom Extension Method
Create a custom extension method to filter a collection. This method returns an IEnumerable<T> and can be used on the query instead of the Where method.
public static class ProductHelper
{
public static IEnumerable<Product> ByColor(this IEnumerable<Product> query, string color)
{
return query.Where(product => product.Color == color);
}
}
List<Product> products = GetProducts();
//Method Syntax
List<Product> filterProducts = products
.ByColor("Red")
ToList();
//Query Syntax
List<Product> filterProducts = (from product in products
select product)
.ByColor("Red")
.ToList();
Summary
This article covered how to filter data in collections using LINQ. We explored filtering with single and multiple fields using AND and OR conditions, and created a custom extension method. These techniques can be used with any IEnumerable or IQueryable types.