views:

292

answers:

3

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?

+17  A: 

in 3.5 and up

array_1.Contains(variable_1);

or 2.0

array_1.IndexOf(variable_1) != -1

Updated: to save on performance

Glennular
Creating a new list just for the sake of finding a value feels like overkill to me. Even in 2.0 you can use Array.IndexOf, Array.Exists, Array.FindIndex etc.
Jon Skeet
Indeed! array_1.IndexOf(variable_1) != -1 should do the job
Junior Mayhé
+1  A: 

mmm there can be various options,

var hasItem = Array.Exists(array_1, x => x == variable_1);
Jhonny D. Cano -Leftware-
+19  A: 

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);
Jon Skeet
Worked perfectly, thanks!
Soo