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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well something has to loop. Any of the following will work:
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:
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>: