使用 LINQ 查询获取索引值集合 [英] Getting a collection of index values using a LINQ query
本文介绍了使用 LINQ 查询获取索引值集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有更好的方法来做到这一点?
Is there a better way to do this?
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);
即我正在寻找一种更有效或更优雅的方式来获取符合条件的项目的位置.
i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.
推荐答案
您可以轻松添加自己的扩展方法:
You could easily add your own extension method:
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"));
这篇关于使用 LINQ 查询获取索引值集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文