是否有可能做一个For ...每个循环向后? [英] Is it possible to do a For...Each Loop Backwards?

查看:143
本文介绍了是否有可能做一个For ...每个循环向后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不相信这是可能的传统方法,但像这样的详细代码:

  For Each s As字符串在myStringList中步骤-1 
//'在这里做东西
下一个

我可能必须颠倒myString对象之前的一个传统的For..Each循环,正确吗?

解决方案

在答案是非常误导。 For Each 的顺序是由它所调用的集合定义的(即它的实现 IEnumerable / IEnumerable< T> ),但不是 许多集合(如数组, List< T> 等)总是以自然顺序进行。

部分文档暗示了这一点:


遍历顺序。当您执行
对于Each ... Next循环时,
集合的遍历由
GetEnumerator方法返回的
枚举器对象控制。
遍历的顺序不是由Visual
Basic决定的,而是由枚举器对象的MoveNext
方法决定的。这个
意味着你可能无法
预测
集合的哪个元素是元素中第一个返回
,或者下一个是
在给定的元素之后返回。

这不完全相同,说它不能被依赖 - 它可以被依赖如果您知道您正在迭代的集合将按照所需的顺序生成结果 。这不像是随机挑选元素。在 IEnumerable / IEnumerable< T> 方面的行为在该页面上明确定义。



可预测排序最重要的例外是字典和集合,它们自然是无序的。

要将 IEnumerable< T> ,使用 Enumerable.Reverse - 但是如果您需要对按位置进行索引的集合(例如数组或 List< T> ),那么最后使用 For 循环会更有效率,并且可以反向工作。


I don't believe this is possible by conventional methods, but something like this verbose code:

For Each s As String In myStringList Step -1
    //' Do stuff here
Next

I will probably have to invert the myString object before a conventional For..Each Loop, correct?

解决方案

I think the documentation referenced in the answer is extremely misleading. The order of For Each is defined by the collection it's called (i.e. its implementation of IEnumerable/IEnumerable<T>), but that's not the same as saying it shouldn't be used when the order is important. Many collections (such as arrays, List<T> etc) always go in the "natural" order.

Part of the documentation does allude to this:

Traversal Order. When you execute a For Each...Next loop, traversal of the collection is under the control of the enumerator object returned by the GetEnumerator method. The order of traversal is not determined by Visual Basic, but rather by the MoveNext method of the enumerator object. This means that you might not be able to predict which element of the collection is the first to be returned in element, or which is the next to be returned after a given element.

That's not at all the same as saying it can't be relied upon - it can be relied upon if you know that the collection you're iterating over will produce the results in the desired order. It's not like it's going to pick elements at random. The behaviour in terms of IEnumerable/IEnumerable<T> is clearly defined on that page.

The most important exceptions to predictable orderings are dictionaries and sets, which are naturally unordered.

To reverse an IEnumerable<T>, use Enumerable.Reverse - but if you need to iterate in reverse over a collection which is indexed by position (such as an array or List<T>) then it would be more efficient to use a For loop starting at the end and working backwards.

这篇关于是否有可能做一个For ...每个循环向后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆