Array.Exists Example
This page was last reviewed on Nov 8, 2023.
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.
Shows an array
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.
Shows an array
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.
return bool
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.
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.
This page was last updated on Nov 8, 2023 (edit).
© 2007-2024 Sam Allen.