在数组中查找多个索引
说我有这样的数组
string [] fruits = {"watermelon","apple","apple","kiwi","pear","banana"};
是否有内置函数允许我查询“apple”的所有索引? 例如,
fruits.FindAllIndex("apple");
将返回1和2的数组
如果没有,我该如何实施呢?
谢谢!
一种方法是这样写:
var indices = fruits .Select ((f, i) => new {f, i}) .Where (x => xf == "apple") .Select (x => xi);
或传统方式:
var indices = new List(); for (int i = 0; i < fruits.Length; i++) if(fruits[i] == "apple") indices.Add(i);
LINQ版本:
var indexes = fruits.Select((value, index) => new { value, index }) .Where(x => x.value == "apple") .Select(x => x.index) .ToList();
非LINQ版本,使用Array
静态方法:
var indexes = new List(); var lastIndex = 0; while ((lastIndex = Array.IndexOf(fruits, "apple", lastIndex)) != -1) { indexes.Add(lastIndex); lastIndex++; }