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 的元素以外的元素
基础教程推荐
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
