有没有办法使用直循环迭代ValueCollection? (不是全部)“for循环”为ValueCollection
例如
Dictionary<string, List<long>>.ValueCollection somevalues = somecollection.Value.Values;
for(int i = 0; i< somevalues.Count; i++)
{
//now what?
}
有没有办法使用直循环迭代ValueCollection? (不是全部)“for循环”为ValueCollection
例如
Dictionary<string, List<long>>.ValueCollection somevalues = somecollection.Value.Values;
for(int i = 0; i< somevalues.Count; i++)
{
//now what?
}
不 - 没有索引器或任何类似的ValueCollection
。我想你可以使用:
for (int i = 0; i < someValues.Count; i++)
{
var item = someValues.ElementAt(i);
...
}
但会像狗一样:)执行
你为什么要(就迭代会为O(n^2),因为它会像Schlemiel the Painter。)去做这个?如果你想要元素的项目,只需保留一个计数器或使用overload of Select
that passes in the index as well as the item。
Lol,不错的一个Jon。 +1 :-) ToArray()会比ElementAt()更具表现力,但与foreach相比,它仍然是浪费时间。 – 2009-07-08 22:25:07
并非开箱即用。一些收藏品没有索引运营商(myCollection[ someIndex ]
)
你不有在for循环中使用索引...
for (var en = somevalues.GetEnumerator(); en.MoveNext();)
{
var item = en.Current;
// do something useful...
}
这不就是`foreach`不太可读的版本吗? (而且它也没有配置枚举器。) – LukeH 2009-07-08 22:59:58
你想为这最可能的原因是能够使用该索引在一些其他的方式。只需使用foreach循环,在循环之前将变量初始化为零,并在循环底部增加它。
为什么你不想使用`foreach`?如果你需要知道当前项目的索引,你可以只保留一个计数器变量,或使用由Jon提到的Select的超载... – 2009-07-08 23:18:11