How to filter collections with LINQ Where
The LINQ Where() method filters a collection based on a predicate function. It returns an IEnumerable<T> containing only elements that satisfy the condition.
You can use lambda expressions or method references as predicates. The Where() method uses deferred execution, meaning it doesn't evaluate until you iterate or call methods like ToList().
Multiple Where() clauses can be chained together, or you can combine conditions with && and || operators in a single Where().
Basic Filtering
C# Example Code
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Filter even numbers
var evenNumbers = numbers.Where(n => n % 2 == 0);
Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers));
// Filter with multiple conditions
var filteredNumbers = numbers.Where(n => n > 3 && n < 8);
Console.WriteLine("Between 3 and 8: " + string.Join(", ", filteredNumbers));Filtering Strings
C# Example Code
// Filter strings
var names = new List<string> { "Alice", "Bob", "Charlie", "David", "Anna" };
var aNames = names.Where(name => name.StartsWith("A"));
Console.WriteLine("Names starting with A: " + string.Join(", ", aNames));Filtering with Index
C# Example Code
// Filter with index
var indexedFilter = numbers.Where((n, index) => index % 2 == 0);
Console.WriteLine("Every other element: " + string.Join(", ", indexedFilter));Chaining Where Clauses
C# Example Code
// Chaining Where clauses
var complexFilter = numbers
.Where(n => n > 2)
.Where(n => n < 9)
.Where(n => n % 2 != 0);
Console.WriteLine("Complex filter: " + string.Join(", ", complexFilter));Filtering Custom Objects
C# Example Code
// Filter objects
var people = new List<Person>
{
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
};
var adults = people.Where(p => p.Age >= 30);
Console.WriteLine("\nAdults (30+):");
foreach (var person in adults)
{
Console.WriteLine($" {person.Name}: {person.Age}");
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}