Подтвердить что ты не робот

С# Array.FindAllIndexOf, который FindAll IndexOf

Я знаю, что С# имеет Array.FindAll и Array.IndexOf.

Есть ли Array.FindAllIndexOf, который возвращает int[]?

4b9b3361

Ответ 1

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

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

Это вернет 0, 2

Если значение не существует в массиве, оно возвращает int [0].

сделать для него метод расширения

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();
    }
}

и назовите его как

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

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

Ответ 2

Вы можете написать что-то вроде:

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

или

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

Прочитайте: Получить индекс данного элемента с помощью LINQ

Ответ 3

Ищет элемент, который соответствует условиям, определенным указанным предикатом, и возвращает весь нулевой индекс вхождения во всем System.Array.

public static int[] FindAllIndex<T>(this T[] array, Predicate<T> match)
{
    return array.Select((value, index) => match(value) ? index : -1)
            .Where(index => index != -1).ToArray();
}

Ответ 4

Нет, нет. Но вы можете написать собственный метод расширения.

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();
}

а затем для вашего массива вызовите его.

Ответ 5

Вы можете выполнить цикл с findIndex, указав индекс

string[] arr = { "abc", "asd", "def", "abc", "lmn", "wer" };
int index = -1;
do
{
    index = Array.IndexOf(arr, "abc", index + 1);
    System.Console.WriteLine(index);
} while (-1 != index);

Ответ 6

Я использовал ответ Nikhil Agrawal для создания следующего связанного метода, который может быть полезен.

public static List<int> FindAllIndexOf<T>(List<T> values, List<T> matches)
    {
        // Initialize list
        List<int> index = new List<int>();

        // For each value in matches get the index and add to the list with indexes
        foreach (var match in matches)
        {
            // Find matches 
            index.AddRange(values.Select((b, i) => Equals(b, match) ? i : -1).Where(i => i != -1).ToList());

        }

        return index;
    }

Что берет список со значениями и список со значениями, которые должны быть сопоставлены. Он возвращает список целых чисел с индексом совпадений.

Ответ 7

Я знаю, что на этот вопрос уже дан ответ, это еще один способ сделать это. обратите внимание, что вместо int[]

я использовал ArrayList
// 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++;
}