Alex Rivera | Logout

c# Array.FindAllIndexOf which FindAll IndexOf

Asked 2012-05-04T06:02:33.637
39

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

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

Edit
Report

2 Answers

47
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");
answered 2012-05-04T06:09:51.637
2

No, there is not. But you can write your own extension method.

public static int[] FindAllIndexOf<T>(this T[] a, Predicate<T> match)
{
   T[] subArray = Array.FindAll<T>(a, match);
   return (from T item in subArray select Array.IndexOf(a, item)).ToArray();
}

and then, for your array, call it.

answered 2012-05-04T06:24:08.753

Your Answer