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 的元素以外的元素


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01