有更好的方法吗?
string[] s = {"zero", "one", "two", "three", "four", "five"};
var x =
s
.Select((a,i) => new {Value = a, Index = i})
.Where(b => b.Value.StartsWith("t"))
.Select(c => c.Index);
即我正在寻找一种更有效或更优雅的方式来获取符合条件的项目的位置。
最佳答案
您可以轻松添加自己的扩展方法:
public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
int index=0;
foreach (T element in source)
{
if (predicate(element))
{
yield return index;
}
index++;
}
}
然后将其用于:
string[] s = {"zero", "one", "two", "three", "four", "five"};
var x = s.IndexesWhere(t => t.StartsWith("t"));
关于c# - 使用 LINQ 查询获取索引值的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/237377/