c# Array.FindAllIndexOf which FindAll IndexOf

Eric Yin picture Eric Yin · May 4, 2012 · Viewed 26.8k times · Source

I know c# has Array.FindAll and Array.IndexOf.

Is there a Array.FindAllIndexOf which returns int[]?

Answer

Nikhil Agrawal picture Nikhil Agrawal · May 4, 2012
string[] myarr = new string[] {"s", "f", "s"};

int[] v = myarr.Select((b,i) => b == "s" ? i : -1).Where(i => i != -1).ToArray();

This will return 0, 2

If the value does not exist in the array then it will return a int[0].

make an extension method of it

public static class EM
{
    public static int[] FindAllIndexof<T>(this IEnumerable<T> values, T val)
    {
        return values.Select((b,i) => object.Equals(b, val) ? i : -1).Where(i => i != -1).ToArray();
    }
}

and call it like

string[] myarr = new string[] {"s", "f", "s"};

int[] v = myarr.FindAllIndexof("s");