C# Find Index of Specific Element in Array
To find index of first occurrence of a specific element in given array in C#, call Array.IndexIf() method and pass the array and the element to search in this array as arguments.
Example
In the following example, we take an array of strings arr, and find the index of first occurrence of element 'cherry' in this array.
Program.cs
</>
Copy
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string[] arr = {"apple", "banana", "cherry", "mango", "cherry"};
string searchElement = "cherry";
int index = Array.IndexOf(arr, searchElement);
Console.WriteLine("Index of '" + searchElement + "' : " + index);
}
}
}
Output
Index of 'cherry' : 2
Conclusion
In this C# Tutorial, we learned how to find the index of a specific element in the array, with examples.
