find the index of an element in an array in csharp

To find the index of an element in an array in C#, you can make use of the IndexOf method of the Array class. Here's an example code snippet:

main.cs
int[] arr = { 1, 3, 5, 7, 9 };
int index = Array.IndexOf(arr, 5);

if (index != -1)
{
    Console.WriteLine("The index of 5 is {0}", index);
}
else
{
    Console.WriteLine("5 not found in the array");
}
203 chars
12 lines

In this code, we first declare an integer array arr containing some values. We then use the IndexOf method to find the index of the element 5 in the array. If the element is found, the method returns its index. If the element is not found, the method returns -1.

We then check if the index returned by the method is -1 or not. If it's not -1, we print out the index of the element. Otherwise, we print out a message saying that the element was not found in the array.

related categories

gistlibby LogSnag