0
0
CsharpHow-ToBeginner · 3 min read

How to Use Array.Find in C# to Search Arrays

Use Array.Find in C# to search an array for the first element that matches a condition defined by a Predicate delegate. It returns the found element or the default value if none matches.
📐

Syntax

The Array.Find method requires two parts: the array to search and a Predicate that defines the condition to find the element.

  • array: The array you want to search.
  • Predicate<T> match: A function that takes an element and returns true if it matches the condition.
csharp
T Array.Find<T>(T[] array, Predicate<T> match);
💻

Example

This example shows how to find the first even number in an integer array using Array.Find.

csharp
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 3, 7, 10, 15, 20 };
        int firstEven = Array.Find(numbers, n => n % 2 == 0);
        Console.WriteLine($"First even number: {firstEven}");
    }
}
Output
First even number: 10
⚠️

Common Pitfalls

Common mistakes when using Array.Find include:

  • Not providing a valid Predicate function, which causes a compile error.
  • Expecting Array.Find to return all matching elements; it only returns the first match.
  • Not handling the case when no element matches, which returns the default value (e.g., 0 for int, null for reference types).

Always check the result before using it if the array might not contain a matching element.

csharp
using System;

class Program
{
    static void Main()
    {
        string[] words = { "apple", "banana", "cherry" };

        // Wrong: expecting all matches
        // string result = Array.Find(words, w => w.Contains("a")); // returns only first match

        // Right: use Array.FindAll for all matches
        string[] results = Array.FindAll(words, w => w.Contains("a"));
        foreach (var word in results)
        {
            Console.WriteLine(word);
        }
    }
}
Output
apple banana
📊

Quick Reference

  • Purpose: Find first element matching a condition.
  • Return: Element found or default value.
  • Input: Array and a predicate function.
  • Use Array.FindAll for multiple matches.

Key Takeaways

Array.Find returns the first element that matches the given condition in an array.
You must provide a Predicate delegate that defines the matching condition.
If no element matches, Array.Find returns the default value for the type.
Use Array.FindAll to get all matching elements instead of just one.
Always check the result before using it to avoid unexpected default values.