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

前端 未结 13 2199
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 04:45

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

     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
    

提交回复
热议问题