是否可以向后执行 For...Each 循环? [英] Is it possible to do a For...Each Loop Backwards?

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

问题描述

我不相信通过传统方法可以做到这一点,但类似于以下冗长的代码:

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

我可能需要在传统的 For..Each 循环之前反转 myString 对象,对吗?

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

推荐答案

我认为 Mike 在下面的回答中引用的文档误导性的.For Each 的顺序由它调用的集合定义(即 IEnumerable/IEnumerable 的实现),但那是 not 就像说当顺序很重要时不应该使用它一样.许多集合(例如数组、List 等)总是以自然"顺序进行.

I think the documentation referenced in Mike's answer below 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:

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

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.

这与说它不能被依赖完全不同——它可以被依赖如果你知道你正在迭代的集合会以期望的顺序产生结果.它不像是随机选择元素.IEnumerable/IEnumerable 方面的行为在该页面上有明确定义.

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.

要反转 IEnumerable,请使用 Enumerable.Reverse - 但是如果您需要反向迭代按位置索引的集合(例如数组或 List),则使用 For 循环从末尾开始并向后工作会更有效.

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...Each 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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