Array.Exists
This C# method tests a condition. It returns true if an element matches that condition. It returns false otherwise. We pass a predicate method instance to Array.Exists
.
When we call Array.Exists
, we are calling a loop in a declarative way. This can reduce some issues with maintaining a lot of loops.
Exists
exampleTo start, this example program creates a string
array of 2 string
literals. Then it invokes the Array.Exists
method 3 times.
string
value "cat." This call returns true.Exists
searches for an element with the value "python." There is no "python," so this returns false.using System; string[] array = { "cat", "bird" }; // Version 1: test for cat. bool a = Array.Exists(array, element => element == "cat"); Console.WriteLine(a); // Version 2: test for python. bool b = Array.Exists(array, element => element == "python"); Console.WriteLine(b); // Version 3: see if anything starts with "d." bool c = Array.Exists(array, element => element.StartsWith("d")); Console.WriteLine(c);True False False
For Array.Exists
, we can pass the name of a static
method that receives the type of the array elements and returns a bool
. We do not need to use lambda syntax.
using System; class Program { static bool IsLowNumber(int number) { return number <= 20; } static void Main() { Console.WriteLine(Array.Exists(new int[]{ 200, 300, 400 }, IsLowNumber)); } }False
How does the Array.Exists
method work? It contains a for
-loop that iterates through every array element calls the predicate function on each element.
Array.Exists
method has substantial overhead. The arguments of the method must be checked by the runtime.for
-loop would be faster.Array.Exists()
searches for an element that matches a certain predicate condition. It involves some overhead and performance drawbacks.