How to find index of item in array in C#

By FoxLearn 10/25/2024 9:07:53 AM   76
To find the index of an item in an array in C#, you can use Array.IndexOf or Array.FindIndex method.

Using Array.IndexOf in C#

The Array.IndexOf method searches for the specified object and returns the index of its first occurrence within the array. If the item is not found, it returns -1.

For example:

int[] numbers = { 10, 20, 30, 40, 50 };
int itemToFind = 30;

int index = Array.IndexOf(numbers, itemToFind);

You can use Array.IndexOf for any type of array, whether it's integers, strings, or custom objects, as long as the type implements equality comparison.

Using Array.FindIndex in C#

For example:

string[] answers = new string[] {"A","B","C","D"}
var index = Array.FindIndex(answers, x => x == "A");

In C#, Array.FindIndex is a method that allows you to find the index of an element in an array based on a specific condition defined by a predicate.

In this case, x => x == "A" is a lambda expression that checks if the number is equal to "A".

If you have an array of custom objects, you can use Array.FindIndex like this:

class Person
{
    public string Name { get; set; }
}

//Main.cs
Person[] people = {
            new Person { Name = "Alice" },
            new Person { Name = "Bob" },
            new Person { Name = "Charlie" }
        };

// Find index of person with Name "Bob"
int index = Array.FindIndex(people, person => person.Name == "Bob");

Array.FindIndex is useful for finding an index based on conditions. You can define complex conditions using a lambda expression and it works with any data type, including custom objects.