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().
C# Example Code
using System;
using System.Collections.Generic;
using System.Linq;
public class LinqWhere
{
public static void Main(string[] args)
{
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));
// 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));
// Filter with index
var indexedFilter = numbers.Where((n, index) => index % 2 == 0);
Console.WriteLine("Every other element: " + string.Join(", ", indexedFilter));
// 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));
// 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;
}
}