问题描述
我正在考虑为我的自定义集合(一棵树)实现 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 的元素以外的元素开始迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)