Reputation: 11
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
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
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