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