Let's say I have a C# variable and array:
int variable_1 = 1;
int[3] array_1 = {1,2,3};
How can I check if the value of variable_1 is equal to any of the values in array_1 without looping through array_1?
A simple way is to run a loop and compare elements one by one. Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).
compareArray() will compare elements of both of the array elements and returns 0 if all elements are equal otherwise function will return 1.
Advantages over variables An array is considered to be a homogenous collection of data. Here the word collection means that it helps in storing multiple values which are under the same variable. For any purpose, if the user wishes to store multiple values of a similar type, an array is the best option that can be used.
Well something has to loop. Any of the following will work:
bool exists = array.Contains(variable_1);
bool exists = Array.IndexOf(array_1, variable_1) != -1;
bool exists = Array.Exists(array_1, x => x == variable_1);
bool exists = Array.FindIndex(array_1, x => x == variable_1) != -1;
bool exists = array_1.Any(x => x == variable_1);
All of the versions using a lambda expression feel like overkill to me, but they're potentially useful if you find yourself in a situation where you don't know the actual value you're searching for - just some condition.
If you know that the array is sorted, you can use:
bool exists = Array.BinarySearch(array_1, variable_1) >= 0;
That will be O(log n) rather than O(n) (which all the others are), but it does require the array to be sorted first.
Personally I'd normally go with the very first form - assuming you're using .NET 3.5 or higher.
If you need to check for several items and the array is large, you may want to create a HashSet<int>
:
HashSet<int> hashSet = new HashSet<int>(array_1);
bool exists = hashSet.Contains(variable_1);
in 3.5 and up
array_1.Contains(variable_1);
or 2.0
array_1.IndexOf(variable_1) != -1
Updated: to save on performance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With