linq 在数组中查找多个索引

o2g1uqev  于 2022-12-06  发布在  其他
关注(0)|答案(3)|浏览(197)

假设我有一个这样的数组

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

有没有一个内置的函数可以让我查询“apple”的所有索引?例如,

fruits.FindAllIndex("apple");

将返回1和2的数组
如果没有,我应该如何执行?
谢谢你!

rm5edbpk

rm5edbpk1#

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++;
}
yhived7q

yhived7q2#

一种方法是这样写:

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);
1qczuiv0

1qczuiv03#

使用扩展方法非常简单。

var fruits = new[] { "watermelon","apple","apple","kiwi","pear","banana" };
var indexes = fruits.FindAllIndexes("apple");

public static class Extensions
{
  public static int[] FindAllIndexes(this string[] array, string search) => array
      .Select((x, i) => (x, i))
      .Where(value => value.x == search)
      .Select(value => value.i)
      .ToArray();
}

相关问题