0
0
CsharpHow-ToBeginner · 3 min read

How to Use List.FindAll in C# to Filter Lists

Use List.FindAll in C# to get all elements from a list that match a condition defined by a Predicate<T>. It returns a new list containing only the elements that satisfy the condition you specify in the predicate function.
📐

Syntax

The List.FindAll method takes a Predicate<T> delegate as a parameter. This delegate defines the condition to filter the list elements.

  • List<T>.FindAll(Predicate<T> match): Returns a new list with all elements that satisfy the match condition.
  • Predicate<T>: A function that takes an element of type T and returns true if the element matches the condition, otherwise false.
csharp
List<T> filteredList = originalList.FindAll(item => condition);
💻

Example

This example shows how to use FindAll to get all even numbers from a list of integers.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        // Find all even numbers
        List<int> evenNumbers = numbers.FindAll(n => n % 2 == 0);

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

Common Pitfalls

Common mistakes when using FindAll include:

  • Not providing a valid predicate function, which causes a compile error.
  • Modifying the original list inside the predicate, which can cause unexpected behavior.
  • Expecting FindAll to modify the original list; it returns a new list instead.

Example of a wrong and right way:

csharp
// Wrong: Modifying list inside predicate (do not do this)
// List<int> result = numbers.FindAll(n => { numbers.Remove(n); return n % 2 == 0; });

// Right: Just check condition without modifying list
List<int> result = numbers.FindAll(n => n % 2 == 0);
📊

Quick Reference

MethodDescription
FindAll(Predicate match)Returns a new list with all elements matching the condition.
PredicateA function that returns true for elements to include.
ReturnsList containing filtered elements.

Key Takeaways

Use List.FindAll with a predicate to filter elements easily.
The method returns a new list; it does not change the original list.
The predicate must be a function returning true for matching elements.
Avoid modifying the list inside the predicate function.
FindAll is useful for simple, readable filtering of lists.