Array.Find
This C# method searches an array (with declarative syntax). We specify a Predicate
type instance to determine what logic the search uses.
Array.Find
allows us to use a for
-loop without having to maintain loop indexes. It eases maintenance. We can also use FindLast
and FindIndex
.
Find
exampleThis program shows how the Array.Find
static
method can be used on the Array type. This is a static
method. It is found in the abstract
base class
for all array types.
Predicate
that receives an element and returns true or false.Array.Find
and Array.FindAll
return the default value (null
or zero).using System; // Use this array of string references. string[] array1 = { "cat", "dog", "carrot", "bird" }; // Find first element starting with substring. string value1 = Array.Find(array1, element => element.StartsWith("car", StringComparison.Ordinal)); // Find first element of three characters length. string value2 = Array.Find(array1, element => element.Length == 3); // Find all elements not greater than four letters long. string[] array2 = Array.FindAll(array1, element => element.Length <= 4); Console.WriteLine(value1); Console.WriteLine(value2); Console.WriteLine(string.Join(",", array2));carrot cat cat,dog,bird
FindLast
exampleFindLast
does the same thing as Find
but searches from the final element. It proceeds backwards, searching each preceding element in order.
string
element in the string array. It searches for the last string
that is 3 characters long.using System; string[] array = { "dot", "net", "perls" }; // Find last string of length 3. string result = Array.FindLast(array, s => s.Length == 3); Console.WriteLine(result);net
FindIndex
exampleImperative searching of arrays is fast. But sometimes, a declarative method call to locate an index is useful. FindIndex
and FindLastIndex
are helpful.
FindIndex
searches from the start—it returns an index of 1. FindLastIndex
goes in reverse—it returns an index of 3.using System; // Use this input array. int[] array = { 5, 6, 7, 6 }; // Use FindIndex method with predicate. int index1 = Array.FindIndex(array, item => item == 6); // Use LastFindIndex method with predicate. int index2 = Array.FindLastIndex(array, item => item == 6); // Write results. Console.WriteLine("{0} = {1}", index1, array[index1]); Console.WriteLine("{0} = {1}", index2, array[index2]);1 = 6 3 = 6
Find
does a forward linear search with a for
-loop and tests each element with the Predicate
. FindAll
uses the List
type and simply adds each match to this internal list variable.
The Predicate
type is a generic type that encapsulates a method that must return a Boolean
. We usually use the lambda syntax—but we can use an anonymous function.
We used Array.Find
and Array.FindAll
, which return a matching value or array when they succeed. These methods are static
. They can be used with arrays of any element type.