The Array.Find() method searches for an element that matches the specified conditions using predicate delegate, and returns the first occurrence within the entire Array.
1 2 3 |
public static T Find<T>(T[] array, Predicate<T> match); |
As per the syntax, the first parameter is a one-dimensional array to search and the second parameter is the predicate deligate which can be a lambda expression. It returns the first element that satisfy the conditions defined by the predicate expression; otherwise, returns the default value for type T.
The following example finds the first element that matches with string “Toni”.
C# Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp18 { class Program { static void Main(string[] args) { string[] names = { "Steve", "Bill", "Toni", "Ravi", "Mohan", "Salman", "Boski" }; var stringToFind = "Toni"; var result = Array.Find(names, element => element == stringToFind); // returns "Bill" Console.WriteLine(result); Console.ReadKey(); } } } |
Output:
Toni
Example 2:
The following example returns the first element that starts with “B”.
1 2 3 4 5 |
string[] names = { "Steve", "Bill", "Bion", "James", "Mohan", "Salman", "Boski" }; var result = Array.Find(names, element => element.StartsWith("B")); // returns Bill |
Example 3:
The following example returns the first element, whose length is five or more.
1 2 3 4 5 |
string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" }; var result = Array.Find(names, element => element.Length >= 5); // returns Steve |
Notice that the Array.Find()
method only returns the first occurrence and not all matching elements. Use the Array.FindAll()
method to retrieve all matching elements.