Is it possible to do start iterating from an element other than the first using foreach?(是否可以从第一个使用 foreach 的元素以外的元素开始迭代?)
问题描述
我正在考虑为我的自定义集合(一棵树)实现 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 的元素以外的元素开始迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以从第一个使用 foreach 的元素以外的元素


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01