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.
Version 2 This call to Exists searches for an element with the value "python." There is no "python," so this returns false.
Version 3 This method call looks for any element that starts with the letter "d." There is no match, so it 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
Method example. 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
Discussion. 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.
Then Once the predicate reports a match, the function exits. No further elements need be searched.
Detail Using the Array.Exists method has substantial overhead. The arguments of the method must be checked by the runtime.
And The predicate will involve a slowdown each time it is called. Using your own inlined for-loop would be faster.
Summary. Array.Exists() searches for an element that matches a certain predicate condition. It involves some overhead and performance drawbacks.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.