Я знаю, что С# имеет Array.FindAll
и Array.IndexOf
.
Есть ли Array.FindAllIndexOf
, который возвращает int[]
?
Я знаю, что С# имеет Array.FindAll
и Array.IndexOf
.
Есть ли Array.FindAllIndexOf
, который возвращает int[]
?
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");
Вы можете написать что-то вроде:
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
Ищет элемент, который соответствует условиям, определенным указанным предикатом, и возвращает весь нулевой индекс вхождения во всем 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();
}
Нет, нет. Но вы можете написать собственный метод расширения.
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();
}
а затем для вашего массива вызовите его.
Вы можете выполнить цикл с 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);
Я использовал ответ 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;
}
Что берет список со значениями и список со значениями, которые должны быть сопоставлены. Он возвращает список целых чисел с индексом совпадений.
Я знаю, что на этот вопрос уже дан ответ, это еще один способ сделать это. обратите внимание, что вместо 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++;
}