是否可以使用 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。执行以下操作:
Skip
是一个 IEnumerable 函数,可以从当前索引开始跳过您指定的任意数量。另一方面,如果您只想使用前三个,您可以使用.Take
:这些甚至可以配对在一起,所以如果您只想要 4-6你可以做的事情:
Yes. Do the following:
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
:These can even be paired together, so if you only wanted the 4-6 items you could do:
最简单的方法是使用
Skip
方法为此,LINQ to Objects 跳过给定数量的元素:显然只需将 1 更改为任何其他值即可跳过不同数量的元素...
类似地,您可以使用
Take
限制返回的元素数量。您可以在 我的Edulinq 博客系列。
It's easiest to use the
Skip
method in LINQ to Objects for this, to skip a given number of elements:Obviously just change 1 for any other value to skip a different number of elements...
Similarly you can use
Take
to limit the number of elements which are returned.You can read more about both of these (and the related
SkipWhile
andTakeWhile
methods) in my Edulinq blog series.您可以使用 Enumerable.Skip 跳过某些元素并启动它那里。
例如:
但是,如果您正在编写一棵树,您可能希望在树项本身上提供一个成员,该成员将返回一个新的
IEnumerable
,该成员将从那里开始枚举。从长远来看,这可能会更有用。You can use Enumerable.Skip to skip some elements, and have it start there.
For example:
However, if you're writing a tree, you might want to provide a member on the tree item itself that will return a new
IEnumerable<T>
which will enumerate from there down. This would, potentially, be more useful in the long run.如果您想跳过读取
DataGridView
中的行,请尝试此操作如果您想将一个
DataGridView
的内容复制到另一个跳过的行,请尝试此操作,这会复制一个
DataGridView
中的内容DataGridView
到另一个跳过 3 行。If you want to skip reading Rows in a
DataGridView
, try thisIf you want to copy contents of one
DataGridView
to another skipping rows, try this,this copies the contents from one
DataGridView
to another skipping 3 rows.Foreach
将以IEnumerable
实现定义的方式迭代您的集合。因此,尽管您可以跳过元素(如上所述),但从技术上讲您仍然以相同的顺序迭代元素。不确定您想要实现什么,但您的类可能有多个 IEnumerable 属性,每个属性都按特定顺序枚举元素。
Foreach
will iterate over your collection in the way defined by your implementation ofIEnumerable
. So, although you can skip elements (as suggested above), you're still technically iterating over the elements in the same order.Not sure what you are trying to achieve, but your class could have multiple
IEnumerable
properties, each of which enumerates the elements in a specific order.