C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
We specify a Predicate type instance to determine what logic the search uses.
This allows us to use a for-loop without having to maintain loop indexes. It eases maintenance.
You call it with a qualified composite name and use the syntax "Array.Find". The first parameter is an array reference. The second parameter is a Predicate that receives an individual element and returns true or false.
And: You can use the lambda syntax to specify the Predicate definition directly in the method call.
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
The second argument to Find and FindAll is a Predicate instance.
Also, the => token in the syntax simply separates the parameter list from the expression that returns true or false based on those arguments. The Boolean return type is inferred from the syntax.
But: If nothing is found, Array.Find and Array.FindAll return the default value (null or zero).
Internals. Internally, the Find method does a forward linear search with a for-loop and tests each element with the Predicate. The FindAll method uses the List type and simply adds each match to this internal list variable.
Thus: In the .NET Framework, the Array class is implemented with the System.Collections.Generics types.
FindLast. The Array type offers the FindLast method along with the Find method. FindLast does the same thing but searches from the final element. It proceeds backwards, searching each preceding element in order.
C# program that uses Array.FindLast using System; class Program { static void Main() { string[] array = { "dot", "net", "deves" }; // Find last string of length 3. string result = Array.FindLast(array, s => s.Length == 3); Console.WriteLine(result); } } Output net
List. The powerful and convenient List type in the System.Collections.Generic namespace provides a dynamic array. It also can use predicates with its Find method. Its Find method can be used with similar syntax.
And: Using these methods results in more declarative code rather than imperative code. This can ease maintenance.