C# Array.Exists

Array type

You want to determine if an element matching a certain condition exists in your array using the C# programming language. By using the Array.Exists method, you can provide an array and a special predicate method that will test each element; you do not need to write a loop.

Example

Note

To start, this example program uses a string array of three string literals. Then, it invokes the Array.Exists method four times. The first call tests each element in the array for the string value "perls"; this returns true. The second call searches for an element with the value "python"; this returns false. The third call looks for any element that starts with the letter "d", and it returns true; the final call looks for the starting letter "x" and fails.

This C# example program uses the Array.Exists method. It tests every element with a Predicate.

Program that uses Array.Exists method [C#]

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"));

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

Output

True
False
True
False

Implementation

.NET Framework information

So 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. Once the predicate reports a match, the function exits; no further elements need be searched.

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.

Summary

The C# programming language

The Array.Exists method provides a handy way to test for an element that matches a certain predicate condition. Although it involves some overhead and performance drawbacks, it can be useful for certain places where these considerations are not paramount.

Array Types
.NET