Get the list of index for a string in an array?

You can do something as follows

string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
// Get indices of BMW 
var indicesArray = cars.Select((car, index) => car == "BMW" ? index : -1).Where(i => i != -1).ToArray();
// Display indices
Label1.Text = string.Join(", ", indicesArray);

You can try the following,

string[] cars = {"Volvo", "BMW", "Volvo", "Mazda","BMW","BMW"};
//returns **{1,4,5}** as a list
var res = Enumerable.Range(0, cars.Length).Where(i => cars[i] == "BMW").ToList();
//joined items of list as 1,4,5
Label1.Text = string.Join(",", res);

Previous answers are also ok. But I would do it like this if you need to do a lot of similar index searches. Will reduce the amount of code you write in the long term.

public static class SequenceExt
{
    public static IEnumerable<int> FindIndexes<T>(this IEnumerable<T> items, Func<T, bool> predicate)
    {
        int index = 0;
        foreach (T item in items)
        {
            if (predicate(item))
            {
                yield return index;
            }

            index++;
        }
    }
}

use it like this:

string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
var indexes = cars.FindIndexes(s => s.Equals("BMW")).ToArray();

returns 1,4,5

Tags:

C#