- Home /
The question is answered, right answer was accepted
How to check if a value exists in an array (C#)
I am making a level generation algorithm. I have all my objects stored in an array. These objects are determined by numbers. I need to check whether the number "0" exists or not. How do I do this? Thanks
Answer by Johnnemann · Apr 26, 2013 at 12:27 AM
If you're using an actual Array, you can use Array.Find() or Exists() to look for the matching member: http://msdn.microsoft.com/en-us/library/d9hy2xwa.aspx or http://msdn.microsoft.com/en-us/library/yw84x8be.aspx
However, if you use a List instead, you can use List.Contains(), which has a bit easier syntax. http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx
Answer by markwelbar · Jul 24, 2013 at 06:59 AM
you can check simple like the following :
string stringToCheck = "GHI";
string[] stringArray = { "ABC", "DEF", "GHI", "JKL" };
foreach (string x in stringArray)
{
if (x.Equals (stringToCheck))
{
MessageBox.Show("Find the string ..." + x);
}
}
Mark
Answer by sharpcoders · Nov 06, 2013 at 10:36 AM
Its pretty simple, use this
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
return true;
}
else
{
return false;
}
The fastest way to search an array is doing a binary search:
Array.BinarySearch
This website benchmarks other methods as well, but the binary search always came out on top.