Reputation: 23
I have an array of data that I know contains only one of the value I'm searching for but I want to know which position in the array that value is held so I can find the corresponding data in another array.
Something like this
int[] data = new int[] { 2, 7, 4, 9, 1 };
int search = 4;
int result;
for (int i = 0; i < data.Length; i++)
{
if (data[i] == search)
{
result = data[i].Position;
}
}
This certainly seems like something that would be easily done but I just can't seem to find how.
Any help with this is greatly appreciated.
Upvotes: 0
Views: 4509
Reputation: 4911
The short way is to use the Array.IndexOf method :
int[] data = new int[] { 2, 7, 4, 9, 1 };
int search = 4;
int index = Array.IndexOf(data, search);
Upvotes: 2
Reputation: 18792
You may want to optimize your code when doing this:
int[] data = new int[] { 2, 7, 4, 9, 1 };
int search = 4;
int result;
for (int i = 0; i < data.Length; i++)
{
if (data[i] == search)
{
result = i;
break; //This will exit the loop after the first match
//If you do not do this, you will find the last match
}
}
Upvotes: 1