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