Enumerable.Where()
A LINQ extension method that filters a sequence (array or collection) to return only the elements that match a condition.
Syntax
using System.Linq; // Use a lambda expression to filter elements by a condition. IEnumerable<T> result = source.Where(x => condition); // Indexed overload (gives access to both the element and its position). IEnumerable<T> result = source.Where((x, i) => condition);
Method List
| Method | Description |
|---|---|
| Where(predicate) | Returns a lazily evaluated sequence containing only the elements that satisfy the condition. |
| Where((x, i) => ...) | Filters elements using both the element value and its index. |
| OfType<T>() | Extracts only the elements that can be cast to the specified type. |
Sample Code
using System;
using System.Collections.Generic;
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Extract only even numbers.
IEnumerable<int> evens = numbers.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evens)); // 2, 4, 6, 8, 10
// Extract elements greater than 5.
IEnumerable<int> bigOnes = numbers.Where(n => n > 5);
Console.WriteLine(string.Join(", ", bigOnes)); // 6, 7, 8, 9, 10
// Combine multiple conditions (even and greater than 5).
IEnumerable<int> filtered = numbers.Where(n => n % 2 == 0 && n > 5);
Console.WriteLine(string.Join(", ", filtered)); // 6, 8, 10
// Filter a list of strings by a specific condition.
List<string> fruits = new List<string> { "apple", "banana", "cherry", "apricot" };
IEnumerable<string> aFruits = fruits.Where(f => f.StartsWith("a"));
Console.WriteLine(string.Join(", ", aFruits)); // apple, apricot
// Use the indexed overload to get only elements at even indices.
IEnumerable<int> evenIdx = numbers.Where((n, i) => i % 2 == 0);
Console.WriteLine(string.Join(", ", evenIdx)); // 1, 3, 5, 7, 9
// The same result using query syntax (SQL-like).
IEnumerable<int> query = from n in numbers
where n % 2 == 0
select n;
Console.WriteLine(string.Join(", ", query)); // 2, 4, 6, 8, 10
Notes
Where() uses lazy evaluation, so the sequence is not materialized when the method is called. Processing occurs only when the sequence is actually enumerated — for example, by ToList() or a foreach loop.
Where() only filters; it never modifies the original sequence. To use the filtered result as a list, chain a call to ToList().
You can also chain multiple Where() calls to combine conditions. When you need to transform elements while filtering, it is common to combine Where() with Enumerable.Select().
If you find any errors or copyright issues, please contact us.