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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.