0

Possible Duplicate:
List Index Search

I have to get index in an int[] where value would be the same and thus I have to get all the index num for the same value in the int[].

ex.

int[] xx = {4,5,4,3,2}

I am using

Array.indexOf(xx, 4);

it will return 0 but I want to get 0, and 2.

Community
  • 1
  • 1
Kumar
  • 955
  • 5
  • 20
  • 50

5 Answers5

5

How about

int[] xx = {4,5,4,3,2};

int search = 4;

var result = xx.Select((b, i) => b.Equals(search) ? i : -1).Where(i => i != -1);

Read my original answer here.

Community
  • 1
  • 1
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

I don't think there's any built-in one-liner for this (Nikhil's approach is as close as LINQ comes), but it's easy to write:

public static IEnumerable<int> FindAllIndexes(this IEnumerable<T> haystack,
                                              T needle) where T : IEquatable<T>
{
    int index = 0;
    foreach (var item in haystack)
    {
        if (item.Equals(needle))
        {
            yield return index;
        }
        index++;
    }
}

Use it as:

foreach (var index in array.FindAllIndexes(4))
{
    ...
}

You could write an overload using a custom comparer if you really wanted to.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1
using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] xx = { 4, 5, 4, 3, 2 };
        int findValue = 4;
        var indexes = xx.Select((val, index) => new { Value = val, Index = index })
            .Where(x => x.Value == findValue)
            .Select(x => x.Index);
        foreach (var index in indexes)
            Console.WriteLine(index);
    }
}
Denis
  • 5,894
  • 3
  • 17
  • 23
0

You can do it by using iterators.

public IEnumerable<int>
GetIndexes(int[] xx, int toSearch )
{
  // Yield even numbers in the range. 
  for (int i= 0; i < xx.Length; i++)
  {
      if (xx[i] == toSearch)
      {
          yield return xx[i];
      }
  }
}
Adil
  • 146,340
  • 25
  • 209
  • 204
0

You could simply use a method like this (if it's ok to have a sequence rather than an array):

static IEnumerable<int> AllIndexesOf(int[] xx, int value) {
    for (int i = 0; i < xx.Length; ++i) {
        if (xx[i] == 4) {
            yield return i;
        }
    }    
}
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193