iMxAndyy
iMxAndyy

Reputation: 23

How to find the position of an item in an array in c#

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

Answers (3)

Fabien ESCOFFIER
Fabien ESCOFFIER

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

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

nhouser9
nhouser9

Reputation: 6780

Just do

result = i;

i is the position in the array.

Upvotes: 3

Related Questions