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

前端 未结 13 2166
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 03:53

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 stu         


        
相关标签:
13条回答
  • 2020-12-06 04:37

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

    0 讨论(0)
  • 2020-12-06 04:37
    For Each s As String In myStringList.Reverse
        //' Do stuff here
    Next
    
    0 讨论(0)
  • 2020-12-06 04:41

    Sadly, the MSDN docs on For Each state 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.

    Good luck!

    0 讨论(0)
  • 2020-12-06 04:44

    Testig in Framework 4, the code

    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

    0 讨论(0)
  • 2020-12-06 04:45

    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
    
    0 讨论(0)
  • 2020-12-06 04:46

    What you have to do is create an array with your for each you had before, then use array.reverse and run the for each on the array. Done

    Cheers

    0 讨论(0)
提交回复
热议问题