我正在考虑为我的自定义集合(一棵树)实现 IEnumerable,以便我可以使用 foreach 遍历我的树.但是据我所知,foreach 总是从集合的第一个元素开始.我想选择从哪个元素 foreach 开始.是否可以以某种方式更改 foreach 开始的元素?
I'm thinking about implementing IEnumerable for my custom collection (a tree) so I can use foreach to traverse my tree. However as far as I know foreach always starts from the first element of the collection. I would like to choose from which element foreach starts. Is it possible to somehow change the element from which foreach starts?
是的.执行以下操作:
Collection<string> myCollection = new Collection<string>;
foreach (string curString in myCollection.Skip(3))
//Dostuff
Skip
是一个 IEnumerable 函数,它可以从当前索引开始跳过您指定的任意数量.另一方面,如果你想使用 only 前三个你会使用 .Take
:
Skip
is an IEnumerable function that skips however many you specify starting at the current index. On the other hand, if you wanted to use only the first three you would use .Take
:
foreach (string curString in myCollection.Take(3))
这些甚至可以搭配在一起,所以如果你只想要 4-6 件,你可以这样做:
These can even be paired together, so if you only wanted the 4-6 items you could do:
foreach (string curString in myCollection.Skip(3).Take(3))
这篇关于是否可以从第一个使用 foreach 的元素以外的元素开始迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!