6

I have one array:

string[] cars = {"Volvo", "BMW", "Volvo", "Mazda","BMW","BMW"};

I m looking for the index of BMW, and I using below code to get:

Label1.Text = Array.FindIndex(filterlistinput, x => x.Contains("BMW")).ToString();

Unfortunately it return the result for the first BMW index only. Current output:

 1

My expected output will be

{1,4,5}
Ajith
  • 1,447
  • 2
  • 17
  • 31
Shi Jie Tio
  • 2,479
  • 5
  • 24
  • 41

3 Answers3

9

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);
Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32
4

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);
Furkan Öztürk
  • 1,178
  • 11
  • 24
3

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

Koray Elbek
  • 794
  • 5
  • 13