TheDeveloperBlog.com


C# Array.Exists Method Searches Arrays

Array.Exists 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. We do not need a loop.


Example. To start, this example program uses a string array of three string literals. Then, it invokes the Array.Exists method four times. The results are written to the console with Console.WriteLine.

String ArrayConsole.WriteLine

First: The first call tests each element in the array for the string value "perls"—this returns true.

Second: The second call searches for an element with the value "python"—this returns false.

Third: The third call looks for any element that starts with the letter "d", and it returns true.

Fourth: The final call looks for the starting letter "x" and fails, returning false.

C# program that uses Array.Exists method

using System;

class Program
{
    static void Main()
    {
	string[] array = { "cat", "dot", "perls" };

	// Use Array.Exists in different ways.
	bool a = Array.Exists(array, element => element == "perls");
	bool b = Array.Exists(array, element => element == "python");
	bool c = Array.Exists(array, element => element.StartsWith("d"));
	bool d = Array.Exists(array, element => element.StartsWith("x"));

	// Display bools.
	Console.WriteLine(a);
	Console.WriteLine(b);
	Console.WriteLine(c);
	Console.WriteLine(d);
    }
}

Output

True
False
True
False


Discussion. How does the Array.Exists method actually work? It is essentially a wrapper method around a for-loop that loops through every array element sequentially and calls the predicate function on each element.

Then: Once the predicate reports a match, the function exits. No further elements need be searched.

Predicate Type

Using the Array.Exists method has substantial overhead. The arguments of the method must be checked by the runtime. And the predicate itself will involve a slowdown each time it is called.

Therefore: For high-performance code, using your own inlined for-loop would be faster.

Inline Optimization

Summary. The Array.Exists method provides a handy way to test for an element that matches a certain predicate condition. It involves some overhead and performance drawbacks. But it can be useful for certain programs.