1

Calling Array.indexOf(input Array,"A") gives the index of "A" in input Array.But how to get all the index of "A" in the array if "A" occurs more than once in the input Array using a similar function.

iJade
  • 23,144
  • 56
  • 154
  • 243

3 Answers3

3
int[] indexes = input.Select((item, index) => new { item, index })
                     .Where(x => x.item == "A")
                     .Select(x => x.index)
                     .ToArray();
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

You can use following method from Array class

public static int FindIndex<T>(
    T[] array,
    int startIndex,
    Predicate<T> match)

It searches the array starting at startIndex and ending at the last element.

However, it should be used in a loop and in every next iteration the startIndex will be assigned a value = previousIndexFound + 1. Ofcourse, if that's less than the length of array.

Azodious
  • 13,752
  • 1
  • 36
  • 71
0

You can write an extension method for the Array class like this:

public static List<Int32> IndicesOf<T>(this T[] array, T value)
{
    var indices = new List<Int32>();

    Int32 startIndex = 0;
    while (true)
    {
        startIndex = Array.IndexOf<T>(array, value, startIndex);
        if (startIndex != -1)
        {
            indices.Add(startIndex);
            startIndex++;
        }
        else
        {
            break;
        }
    }

    return indices;
}

Usage example:

    var symbols = new Char[] { 'a', 'b', 'c', 'a' };
    var indices = symbols.IndicesOf('a');
    indices.ForEach(index => Console.WriteLine(index));
shadeglare
  • 7,006
  • 7
  • 47
  • 59