在数组中查找多个索引

时间:2013-12-03 19:53:27

标签: c# .net arrays linq

说我有这样的数组

  string [] fruits = {"watermelon","apple","apple","kiwi","pear","banana"};

是否有内置函数允许我查询“apple”的所有索引? 例如,

  fruits.FindAllIndex("apple"); 

将返回1和2的数组

如果没有,我应该如何实施呢?

谢谢!

2 个答案:

答案 0 :(得分:7)

LINQ版本:

var indexes = fruits.Select((value, index) => new { value, index })
                    .Where(x => x.value == "apple")
                    .Select(x => x.index)
                    .ToList();

非LINQ版本,使用Array<T>.IndexOf()静态方法:

var indexes = new List<int>();
var lastIndex = 0;

while ((lastIndex = Array.IndexOf(fruits, "apple", lastIndex)) != -1)
{
    indexes.Add(lastIndex);
    lastIndex++;
}

答案 1 :(得分:6)

一种方法是这样写:

var indices = fruits
                .Select ((f, i) => new {f, i})
                .Where (x => x.f == "apple")
                .Select (x => x.i);

或传统方式:

var indices = new List<int>();
for (int i = 0; i < fruits.Length; i++)
    if(fruits[i] == "apple")
        indices.Add(i);