Eri*_*Yin 24 c# arrays indexof
我知道c#有Array.FindAll
和Array.IndexOf
.
有Array.FindAllIndexOf
退货int[]
吗?
Nik*_*wal 27
string[] myarr = new string[] {"s", "f", "s"};
int[] v = myarr.Select((b,i) => b == "s" ? i : -1).Where(i => i != -1).ToArray();
Run Code Online (Sandbox Code Playgroud)
这将返回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();
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为
string[] myarr = new string[] {"s", "f", "s"};
int[] v = myarr.FindAllIndexof("s");
Run Code Online (Sandbox Code Playgroud)
你可以这样写:
string[] someItems = { "cat", "dog", "purple elephant", "unicorn" };
var selectedItems = someItems.Select((item, index) => new{
ItemName = item,
Position = index});
Run Code Online (Sandbox Code Playgroud)
要么
var Items = someItems.Select((item, index) => new{
ItemName = item,
Position = index}).Where(i => i.ItemName == "purple elephant");
Run Code Online (Sandbox Code Playgroud)
小智 5
搜索与指定谓词定义的条件匹配的元素,并返回整个 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();
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个旧帖子,但您可以尝试以下操作,
string[] cars = {"Volvo", "BMW", "Volvo", "Mazda","BMW","BMW"};
var res = Enumerable.Range(0, cars.Length).Where(i => cars[i] == "BMW").ToList();
Run Code Online (Sandbox Code Playgroud)
以列表形式返回{1,4,5}