0
0
CsharpHow-ToBeginner · 4 min read

How to Filter List in C#: Simple Guide with Examples

In C#, you can filter a list using LINQ with the Where method and a condition inside a lambda expression. This returns a new list containing only the items that match the condition.
📐

Syntax

The basic syntax to filter a list in C# uses the Where method from LINQ. You provide a condition inside a lambda expression that returns true for items to keep.

  • list.Where(item => condition): Filters items based on the condition.
  • item => condition: Lambda expression that tests each item.
  • The result is an IEnumerable which you can convert back to a list with .ToList().
csharp
var filteredList = list.Where(item => condition).ToList();
💻

Example

This example shows how to filter a list of numbers to keep only even numbers using LINQ's Where method.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
        List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

        Console.WriteLine("Even numbers:");
        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}
Output
Even numbers: 2 4 6
⚠️

Common Pitfalls

One common mistake is forgetting to add .ToList() after Where, which leaves you with an IEnumerable instead of a list. Another is using incorrect conditions that always return true or false, resulting in no filtering or an empty list.

Also, modifying the original list while iterating can cause errors.

csharp
/* Wrong: Missing ToList(), result is IEnumerable */
var filtered = numbers.Where(n => n > 3);

/* Right: Convert to List */
var filteredList = numbers.Where(n => n > 3).ToList();
📊

Quick Reference

MethodDescription
Where(predicate)Filters elements based on a condition
ToList()Converts IEnumerable to List
Any()Checks if any elements satisfy a condition
All()Checks if all elements satisfy a condition

Key Takeaways

Use LINQ's Where method with a lambda to filter lists in C#.
Always call ToList() to get a List after filtering if you need list features.
Check your condition carefully to avoid filtering errors.
Avoid modifying a list while iterating over it.
LINQ methods provide clean and readable filtering syntax.