c# Array.FindAllIndexOf which FindAll IndexOf

后端 未结 9 1919
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 08:16

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

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

9条回答
  •  無奈伤痛
    2020-11-29 08:36

    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(this IEnumerable 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");
    

提交回复
热议问题