Click here to Skip to main content
15,918,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to compare single value to whole array
int IDuser=100;
int [] IDUserkey={94,96,98,100};
my condition is if IDuSer not present in IDUserkey (suppose IDUser is 150) ,i want write some code..if IDuser present ok..
please help...
Posted

C#
int IDuser = 100;
           int[] IDUserkey = { 94, 96, 98, 100 };

           if (! IDUserkey.Contains(IDuser))
           {
               // ID User is not present
               // your code here..... 
           }
           else
           {
               // ID User is present
           }



note: add this namespace
C#
using System.Linq;
 
Share this answer
 
v2
Comments
Amol Jadhao 20-Dec-13 1:09am    
thanks karthik
Karthik_Mahalingam 20-Dec-13 1:24am    
welcome amol :)
Cheeck
bool result = IDUserkey.Contains( IDuser);
 
Share this answer
 
Comments
Karthik_Mahalingam 20-Dec-13 1:24am    
right.
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 normally go with the very first form - assuming you are 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)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900