-1

How to find all positions of a value in array

   class Program
    {
        static void Main(string[] args)
        {
            int start = 0;
           int[] numbers = new int[7] { 2,1,2,1,5,6,5};
    }
ivan.mylyanyk
  • 2,051
  • 4
  • 30
  • 37

5 Answers5

1

Something like that:

  int[] numbers = new [] { 2, 1, 2, 1, 5, 6, 5 };
  int toFind = 5;

  // all indexes of "5" {4, 6}
  int[] indexes = numbers
    .Select((v, i) => new {
      value = v,
      index = i
    })
    .Where(pair => pair.value == toFind)
    .Select(pair => pair.index)
    .ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1
List<int> indexes = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] == yourNumber)
        indexes.Add(i);
}
David Pilkington
  • 13,528
  • 3
  • 41
  • 73
0

Useage is: Array.indexOf(T,value)

please refere to the msdn below.

http://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx

meetkichu
  • 131
  • 1
  • 6
0

You can make a really simple extension method for sequences to do this:

public static class SequenceExt
{
    public static IEnumerable<int> IndicesOfAllElementsEqualTo<T>
    (
        this IEnumerable<T> sequence, 
        T target
    )   where T: IEquatable<T>
    {
        int index = 0;

        foreach (var item in sequence)
        {
            if (item.Equals(target))
                yield return index;

            ++index;
        }
    }
}

The extension method works with List<>, arrays, IEnumerable<T> and other collections.

Then your code would look something like this:

var numbers = new [] { 2, 1, 2, 1, 5, 6, 5 };

var indices = numbers.IndicesOfAllElementsEqualTo(5); // Use extension method.

// Make indices into an array if you want, like so
// (not really necessary for this sample code):

var indexArray = indices.ToArray();

// This prints "4, 6":
Console.WriteLine(string.Join(", ", indexArray));
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • I'd rather change extension method's signature to `IEnumerable IndicesOfAllElementsEqualTo(this IEnumerable sequence, Func map)` in order to do it more general – Dmitry Bychenko Sep 16 '14 at 09:46
-1

Linq could help

var indexes = numbers
  .Select((x, idx) => new { x, idx })
  .Where(c => c.x == number)
  .Select(c => c.idx);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184