Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hiii all

i have an array like that:
<br />
int[] Departments = new int[4] { 2, 3, 4, 5 };<br />


and i have another value entered by the user. i want to check if this value is in the array values or not.

i tried :
MIDL
if(x "Not IN" Departments)
      {
      }

but there is an error in it.
can any body help me in that, please???

Thanks
Posted
Updated 3-Jul-11 0:21am
v2

Try:
int[] Departments = new int[4] { 2, 3, 4, 5 };
if (Departments.Contains(3))
    {
    MessageBox.Show("Yes!");
    }
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 3-Jul-11 13:12pm    
My 5, but I added recommendations about collections to improve performance on big data sets, please see.
--SA
In addition to above solution you can also try BinarySearch for checking value is present or not in given set of array.
take a look
C#
int[] Departments = new int[4] { 2, 3, 4, 5 };
 if (Array.BinarySearch(Departments, 3) >= 0)
     {
     //Yes Present
     }
 
Share this answer
 
v2
Comments
OriginalGriff 4-Jul-11 3:39am    
Just a suggestion - don't refer to "the above solution". When they get re-ordered due to votes, it can look like you are referring to a completely different answer. Try saying "[name of user]'s solution" instead.
RaviRanjanKr 4-Jul-11 5:38am    
Got it. Thanks OriginalGriff :)
OriginalGriff 4-Jul-11 5:48am    
You're welcome!
Of course, if you want to check for "not in", and using Griff's example above, it would be:

C#
if (!Departments.Contains(3))
{
   MessageBox.Show("The value 3 is not in Departments".")
}
 
Share this answer
 
If you really need performance you should use some (temporary) container with faster access. With the array, you have performance of O(n) (see http://en.wikipedia.org/wiki/Big_O_notation[^]).

Consider System.Collections.Generic.SortedList, System.Collections.Generic.SortedDictionary and System.Collections.Generic.Dictionary. They have different access times O(log(n)) to the best O(1) in Dictionary, different insertion times and memory overheads.

Please see for more detail:
http://msdn.microsoft.com/en-us/library/system.collections.sortedlist(v=VS.100).aspx[^],
http://msdn.microsoft.com/en-us/library/f7fta44c(v=VS.100).aspx[^],
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx[^].

—SA
 
Share this answer
 
if (!Departments.Contains(x))
{

}
 
Share this answer
 
hi,

you can also use looping
for(int i=0;i<departments.length,i++)>
{
if(Departments[i]==5)
{
messageBox.Show("Element Exists");
}
}
 
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