Filtering Down Objects with Where
The Where
method is one of the most commonly used LINQ methods in .NET for filtering collections.
- It allows you to filter objects based on a condition or set of conditions.
Where
takes a predicate, which is a function that returnstrue
orfalse
based on whether the object should be included in the result set.
Source Code and Func<T, bool> Predicate
The Where
method internally uses a Func<T, bool>
predicate to determine which elements should be included in the returned sequence.
Here’s an example of how the Where
method might look in source code:
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
foreach (TSource element in source)
{
if (predicate(element))
{
yield return element;
}
}
}
The Func<T, bool>
predicate in this case represents a function that takes a parameter of type T (the type of the object being filtered) and returns a bool indicating whether the object meets the condition.
Example
var highEarners = employees.Where(e => e.Salary > 100000);
Chaining Where and Select
In LINQ, you can chain methods together to perform multiple operations in sequence. This is particularly useful when combining Where
and Select
to both filter and transform data.
Example Filtering and Projecting Data
var highEarnerNames = employees
.Where(e => e.Salary > 100000)
.Select(e => e.Name);
Here’s what happens:
Where
filters the collection based on salary.Select
then projects the result into a new collection that only contains the employees' names.
Example Multiple Filters with Where
var seniorHighEarners = employees
.Where(e => e.Salary > 100000)
.Where(e => e.YearsOfExperience > 10);
OfType<T>
: Filtering by Type
- If you have an IEnumerable and you want to select objects of a specific type, you can use the OfType
method. This is useful when working with collections that contain mixed types, such as collections of objects.
Example Filtering by Type with OfType<T>
var mixedObjects = new[] {
new Employee(),
new Location(),
new Vendor()
}
var employees = mixedObjects.OfType<Employee>();
OfType<T>
filters the collection, returning only elements of the specified typeT
.- It’s particularly handy when working with non-generic collections like
ArrayList
or collections where multiple types are present.