假设我有一个这样的数组
string [] fruits = {"watermelon","apple","apple","kiwi","pear","banana"};
有没有一个内置的函数可以让我查询“apple”的所有索引?例如,
fruits.FindAllIndex("apple");
将返回1和2的数组如果没有,我应该如何执行?谢谢你!
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()静态方法:
Array<T>.IndexOf()
var indexes = new List<int>(); var lastIndex = 0; while ((lastIndex = Array.IndexOf(fruits, "apple", lastIndex)) != -1) { indexes.Add(lastIndex); lastIndex++; }
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);
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(); }
3条答案
按热度按时间rm5edbpk1#
LINQ版本:
非LINQ版本,使用
Array<T>.IndexOf()
静态方法:yhived7q2#
一种方法是这样写:
还是传统的方式:
1qczuiv03#
使用扩展方法非常简单。