我不相信常规方法可以实现这一点,但是类似于这样冗长的代码:
For Each s As String In myStringList Step -1
//' Do stuff here
Next
在传统的 For..Each 循环之前,我可能需要反转 myString 对象,是吗?
我认为在下面 Mike 的回答中提到的文档 是 非常 误导人的。 For Each
的顺序是由它调用的集合(即其对 IEnumerable
/IEnumerable<T>
接口的实现)定义的,但这并不意味着在需要有序时就不应使用它。许多集合(如数组、List<T>
等)总是按照“自然”顺序排列。
文档的一部分确实暗示了这一点:
遍历顺序。当您执行 For each...Next 循环时,集合的遍历受 GetEnumerator 方法返回的枚举器对象控制。遍历顺序不是由 Visual Basic 决定的,而是由枚举器对象的 MoveNext 方法决定的。这意味着您可能无法预测要在元素中返回的第一个元素或给定元素之后要返回的下一个元素。
这与说它不能被依赖是完全不同的 - 如果您知道正在迭代的集合将以所需顺序产生结果,则可以依赖它。它不会随机选择元素。在 IEnumerable
/IEnumerable<T>
方面的行为在该页面上清楚定义。
最重要的有序例外是字典和集合,它们自然是无序的。
要反转一个IEnumerable<T>
,可以使用 Enumerable.Reverse
方法。但如果需要倒序遍历一个通过位置索引的集合(例如数组或 List<T>
),那么更有效率的方法是使用从结尾开始并向前工作的 For
循环。您需要执行类似以下的操作:
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
但据我所知,您不能倒序使用"For...Each",尽管在某些情况下这将是很好的。
遗憾的是,MSDN关于For Each的文档指出,For Each结构明确用于迭代顺序不重要(无序集合等)的情况。因此,很遗憾没有反转For Each的概念,因为顺序本身就没有定义。
祝你好运!
调用 System.Linq.Enumerable.Reverse
方法,以获取与您的可枚举源相反顺序的 IEnuemrable(Of TSource)
。
reverse方法
,因此它是仅链接的(两个点赞我的评论的用户似乎也同意)。请至少编辑您的问题以扩展您的答案。 - AStopher在Framework 4中进行测试,代码如下:
For Each s As String In myStringList.Reverse
//' Do stuff here
Next
它之前无法工作,正确的做法是:
myStringList.Reverse() ' it is a method not a function
For Each s As String In myStringList
//' Do stuff here
Next
For Each s As String In myStringList.Reverse
//' Do stuff here
Next
Dim myArray() As String = {"1", "2", "3", "4", "5"}
For Each n As String In myArray.Reverse
Debug.Print(n)
Next
输出:5 4 3 2 1
'
这也可以运行:Dim myArray() As String = {"1", "2", "3", "4", "5"}
For i As Integer = myArray.Length - 1 To 0 Step -1
Debug.Print(myArray(i))
Next
输出:5 4 3 2 1
你可以为你想要反转的类添加一个扩展函数
<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
然后你会这样调用它
For Each s As Something In SomeCollection.Reverse
Next
创建一个列表,通过 For 循环收集
dim revList as New List (of ToolStripItem)
For each objItem as ToolStripItem in Menu.DropDownItems
revList.Add(objItem)
next
revList.reverse ' reverse the order of that list
逆序遍历列表
for each objItem as ToolStripItem in revList
' do whatever (like removing your menu from an ArrayMenu)
next
请将ToolStripItem和Menu.DropDownItems替换为您需要的内容