Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing One Value To A Whole Array? (C#)

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?

like image 838
sooprise Avatar asked Apr 05 '10 16:04

sooprise


People also ask

How do you compare one element to another array?

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).

Can I compare arrays in C?

compareArray() will compare elements of both of the array elements and returns 0 if all elements are equal otherwise function will return 1.

How array is better as compare to variable?

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.


2 Answers

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);
like image 90
Jon Skeet Avatar answered Oct 12 '22 01:10

Jon Skeet


in 3.5 and up

array_1.Contains(variable_1);

or 2.0

array_1.IndexOf(variable_1) != -1

Updated: to save on performance

like image 27
Glennular Avatar answered Oct 12 '22 02:10

Glennular