咨询区
-
Guy
我有下面一段伪代码:.
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);
我想获取集合中是 c
开头项的索引,请注意,这个索引是原数组的索引,不是新集合的索引,请问我该如何实现?
回答区
-
Jon Skeet
非常简单,你可以用 foreach
再配合 yield
来实现,参考如下代码:
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++;
}
}
然后像下面这样使用。
static void Main(string[] args)
{
string[] s = { "zero", "one", "two", "three", "four", "five" };
var x = s.IndexesWhere(t => t.StartsWith("t"));
}
-
tvanfosson
如果你仅仅是因为学习 Linq
的话,那可以忽略这个帖子,对我来说,我不清楚 Linq 是不是最终的优秀解决方案,但下面的代码肯定会更高效,而且还不会生成必要的 匿名类型
,参考如下代码:
static void Main(string[] args)
{
string[] s = { "zero", "one", "two", "three", "four", "five" };
List<int> matchingIndices = new List<int>();
for (int i = 0; i < s.Length; ++i)
{
if (s[i].StartWith("t"))
{
matchingIndices.Add(i);
}
}
}
-
Terrence
我有一个好办法可以实现,首先提取出 集合
中的索引值,然后通过 索引值
获取集合元素,参考如下代码:
static void Main(string[] args)
{
string[] s = { "zero", "one", "two", "three", "four", "five" };
var indexes = s.Select((a, i) => i).Where(i => s[i].StartsWith("t"));
}
虽然代码效率上会稍低一些,但我敢保证绝对是最简单的方法。
点评区
各位大佬提供了各种解题思路,哈,学习了。