vb.net 是否可以向后执行 For...Each 循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/952136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:14:58  来源:igfitidea点击:

Is it possible to do a For...Each Loop Backwards?

vb.netfor-loop

提问by Anders

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?

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

回答by Jon Skeet

I think the documentation referenced in Mike's answer belowis extremelymisleading. The order of For Eachis defined by the collection it's called (i.e. its implementation of IEnumerable/IEnumerable<T>), but that's notthe 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.

我认为中引用的文件下方小李的答案非常误导。顺序For Each是由它被称为集合定义(即其执行IEnumerable/ IEnumerable<T>),但是这等于说它不应该被使用时的顺序是非常重要的。许多集合(例如数组List<T>等)总是以“自然”顺序进行。

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.

遍历顺序。当您执行 For Each...Next 循环时,集合的遍历由 GetEnumerator 方法返回的枚举器对象控制。遍历的顺序不是由 Visual Basic 决定的,而是由枚举器对象的 MoveNext 方法决定的。这意味着您可能无法预测集合的哪个元素是 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.

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

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 Forloop starting at the end and working backwards.

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

回答by SqlRyan

You'd have to do something like:

您必须执行以下操作:

For i as integer = myStringList.Count-1 to 0 step -1
    dim s as string = myStringList.Item(i)
    ' Do your stuff with s
Next i

But as far as I know, you can't do a "For...Each" backwards, though that would be nice in a few instances.

但据我所知,您不能向后执行“For...Each”,尽管在某些情况下这会很好。

回答by Mike

Sadly, the MSDN docs on For Eachstate that the For Each construct is there explicitly for cases where the order of the iteration is unimportant (unordered sets and the like). So there is unfortunately no concept of reversing a For Each, as the order is not defined anyway.

遗憾的是,For Each 上MSDN 文档指出 For Each 构造明确存在于迭代顺序不重要的情况(无序集等)。所以不幸的是没有反转 For Each 的概念,因为无论如何都没有定义顺序。

Good luck!

祝你好运!

回答by Amy B

Call the System.Linq.Enumerable.Reversemethod to get an IEnuemrable(Of TSource)in the reverse order of your enumerable source.

调用该System.Linq.Enumerable.Reverse方法以获取与IEnuemrable(Of TSource)可枚举源相反的顺序。

回答by Tonko Boekhoud

For Each s As String In myStringList.Reverse
    //' Do stuff here
Next

回答by Dave

Testig in Framework 4, the code

Testig 在 Framework 4 中,代码

For Each s As String In myStringList.Reverse
    //' Do stuff here
Next

it wasn't working, the right way to do it is:

它不起作用,正确的方法是:

myStringList.Reverse() ' it is a method not a function
For Each s As String In myStringList
//' Do stuff here
Next

Look at: MSDN: Reserve

看:MSDN:保留

回答by reinierpost

The reason it can't be done is that, as a basic design feature, For Each can iterate over an enumerable without a last element, or with an as yet unknown last element.

不能这样做的原因是,作为一个基本的设计特性,For Each 可以迭代一个没有最后一个元素的可枚举,或者一个未知的最后一个元素。

回答by DotNet Programmer

You can add a extended function to the class you are trying to reverse

您可以向您尝试反转的类添加扩展函数

<Serializable()> Public Class SomeCollection
    Inherits CollectionBase
    Public Sub New()
    End Sub

    Public Sub Add(ByVal Value As Something)
        Me.List.Add(Value)
    End Sub

    Public Sub Remove(ByVal Value As Something)
        Me.List.Remove(Value)
    End Sub

    Public Function Contains(ByVal Value As Something) As Boolean
        Return Me.List.Contains(Value)
    End Function

    Public Function Item(ByVal Index As Integer) As Something
        Return DirectCast(Me.List.Item(Index), Something)
    End Function

    Public Function Reverse() As SomeCollection
        Dim revList As SomeCollection = New SomeCollection()
        For index As Integer = (Me.List.Count - 1) To 0 Step -1
             revList.List.Add(Me.List.Item(index))
        Next
        Return revList
    End Function
End Class

Then you would call it like this

然后你会这样称呼它

For Each s As Something In SomeCollection.Reverse

Next

回答by Hisham Shaaban

first you should create a list(of string) in for each statement, and after that make another normal for .. step -1 ..next statement. see an example:

首先,您应该为每个语句创建一个(字符串)列表,然后为 .. step -1 ..next 语句创建另一个正常的列表。看一个例子:

Dim ff As New List(Of Integer)
For Each rRow As DataRow In DeletedRows
Dim item As Integer
item = rRow.Table.Rows.IndexOf(rRow)
ff.Add(item)
Next
For i As Integer = ff.Count - 1 To 0 Step -1
dim item as integer=ff(i)
next i

i hope that be helpful

我希望有帮助

回答by Adam

The accepted answer explains why, but to add another example, for a collection with key (SortedList, SortedDictionary, Dictionary, etc.) you can do

接受的答案解释了原因,但要添加另一个示例,对于带有键(SortedList、SortedDictionary、Dictionary 等)的集合,您可以执行以下操作

For Each Id as Tkey in MyCollection.Keys.Reverse
   // The item in question is now available as MyCollection(Id)
Next