C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Parameters: The first parameter is an array reference. The second is a Predicate that receives an element and returns true or false.
PredicateMain: We use Array.Find and FindAll to perform searches on the array. The second argument to Find and FindAll is a Predicate instance.
Lambda: The => token separates the parameter list from the expression that returns true or false based on those arguments.
But: If nothing is found, Array.Find and Array.FindAll return the default value (null or zero).
C# program that uses Array.Find static method
using System;
class Program
{
static void Main()
{
//
// 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));
}
}
Output
carrot
cat
cat,dog,bird
Here: This example program returns a string element in the string array. It searches for the last string that is 3 characters long.
C# program that uses Array.FindLast
using System;
class Program
{
static void Main()
{
string[] array = { "dot", "net", "Codex" };
// Find last string of length 3.
string result = Array.FindLast(array, s => s.Length == 3);
Console.WriteLine(result);
}
}
Output
net
Arguments: The first argument is the array. The second argument is a lambda expression, which fits the requirement of a predicate.
Note: If the right-side expression evaluates to true, the element matches. And its index is returned.
Info: The lambda expressions are used to locate elements with a value of 6. This makes sense for a short example program.
Finally: FindIndex searches from the start—it returns an index of 1. FindLastIndex goes in reverse—it returns an index of 3.
C# program that uses Array.FindIndex method
using System;
class Program
{
static void Main()
{
// 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]);
}
}
Output
1 = 6
3 = 6
Thus: In the .NET Framework, the Array class is implemented with the System.Collections.Generics types.