C# Array.Exists Example (Search Array)Search elements in an array with a Predicate argument using the Array.Exists method.
dot net perls
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.
Method notes. 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 example. To start, this example program creates a string array of 2 string literals. Then it invokes the Array.Exists method 3 times.
Version 1 The first call tests each element in the array for the string value "cat." This call returns true.
True, False
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.
C# program that uses Array.Exists method
using System; class Program { static void Main() { 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.
Bool Method
C# program that uses method 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)); } }
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.
Performance 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.
A summary. Array.Exists() searches for an element that matches a certain predicate condition. It involves some overhead and performance drawbacks.
© 2007-2021 sam allen. see site info on the changelog