Marissa
Marissa

Reputation: 11

How do I find the position of an element in a C# array

I have a C# array of integers. The integers in the array are all unique. For example the array contains page numbers: 1,2,4,5,7,9

If I am on page 5 I would like to have a previous button to take me to page 4 and 8.

My question is how can I find the index position in an array if I just know it's the row that contains the number "5"?

Hope someone can help.

thanks,

Upvotes: 1

Views: 483

Answers (3)

Gilad Naaman
Gilad Naaman

Reputation: 6550

I think that the following code should work:

static int IndexOf(int[] arr, int input)
{
    for (int i = 0; i < arr.Length - 1; i++)
        if (arr[i] == input) return i;
    return -1;
}

Edit: I didn't know that that method already exists

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

You could use the IndexOf method:

var array = new[] { 1, 2, 4, 5, 7, 9 };
var index = Array.IndexOf(array, 5);

Upvotes: 3

Ed Guiness
Ed Guiness

Reputation: 35267

Array.IndexOf

Upvotes: 6

Related Questions