有沒有辦法使用直循環迭代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