Click here to Skip to main content
15,077,641 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
How can I can get the index of an array element? Is there a method available?

What I have tried:

Updated 6-Aug-21 7:56am

There is the Array.IndexOf[^] method, but it may not return the one you want: it will return the first matching entry. So if you have two elements with the value "9", it will always return the one with the lowest index.
Espen Harlinn 14-Feb-11 4:55am
Nice and easy, a 5
Sergey Alexandrovich Kryukov 14-Feb-11 18:00pm
Correct, my 5.
Hi Mehdi,

Simply you make a loop for searching for that element in your array.

This is an example:

int[] Array = { 5, 8, 3, 7 };
int Element = 3;
int Index;

for (int i = 0; i < Array.Length; i++)
     if (Element == Array[i])
         Index = i;

I hope this help,
Hope Array Index of[^] will guide you.
Answer 1 wil give u the first index of the element in array and answer 2 wil give u the last index

You can use List to keep record of all indexes of element to search

List<int> index_list =new List<int>();
int srch=3;

for (int i = 0; i < Array.Length; i++)
     if (srch == Array[i])

foreach (int index in index_list) // Loop through List with foreach
            // do ur coding for index here


if dont want to use List, then can use string too, see here

Unknown size Numeric Arrays from Strings - dontumindit[^]
lets say:
public int GetIndexOfArray(string Element, string[] Array)
  for ( int i = 0; i < Array.Length; i++)
      if( Element == Array[i])
          return i;
return -1;

int x = GetIndexOfArray(Element, Array);
/*if x = -1 then there is no such Element, else it will return the index of the Element in the Array*/
shadi_abushaar 14-Feb-11 5:46am
this is the Method that you required to get you the index of an element in an array, you just need to give this method the element and the array as an input and it will return the index of the element in the array otherwise it will return -1.. for not finding.. hope it will work with you man..

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