c# Array.FindAllIndexOf which FindAll IndexOf

后端 未结 9 1918
佛祖请我去吃肉
佛祖请我去吃肉 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:57

    I'm aware that the question is answered already, this is just another way of doing it. note that I used ArrayList instead of int[]

    // required using directives
    using System;
    using System.Collections;
    
    String      inputString = "The lazy fox couldn't jump, poor fox!";
    ArrayList   locations   =  new ArrayList();      // array for found indexes
    string[] lineArray = inputString.Split(' ');     // inputString to array of strings separated by spaces
    
    int tempInt = 0;
    foreach (string element in lineArray)
    {
         if (element == "fox")
         {
             locations.Add(tempInt);   // tempInt will be the index of current found index and added to Arraylist for further processing 
         }
     tempInt++;
    }
    
    0 讨论(0)
  • 2020-11-29 09:00

    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.

    0 讨论(0)
  • 2020-11-29 09:03

    You can write something like :

    string[] someItems = { "cat", "dog", "purple elephant", "unicorn" }; 
    var selectedItems = someItems.Select((item, index) => new{
        ItemName = item,
        Position = index});
    

    or

    var Items = someItems.Select((item, index) => new{
        ItemName = item,
        Position = index}).Where(i => i.ItemName == "purple elephant");
    

    Read : Get the index of a given item using LINQ

    0 讨论(0)
提交回复
热议问题