¿Es posible hacer un Para Each Cada Bucle hacia atrás?


No creo que esto sea posible por métodos convencionales, pero algo así como este código detallado:

For Each s As String In myStringList Step -1
    //' Do stuff here
Next

Probablemente tendré que invertir el objeto myString antes de un For convencional..Cada Bucle, ¿correcto?

Author: Anders, 2009-06-04

13 answers

Creo que la documentación a la que se hace referencia en la respuesta es extremadamente engañosa. El orden de For Each está definido por la colección a la que se llama (es decir, su implementación de IEnumerable/IEnumerable<T>), pero eso es no lo mismo que decir que no se debe usar cuando el orden es importante. Muchas colecciones (como arrays, List<T>, etc.) siempre van en el orden "natural".

Parte de la documentación hace alusión a esto:

Orden transversal . Cuando ejecutar una Para Cada Uno...Siguiente bucle, recorrido de la la recogida está bajo el control del objeto enumerador devuelto por el Método GetEnumerator. La orden de el recorrido no está determinado por Básico, sino más bien por el MoveNext método del objeto enumerador. Este significa que es posible que no pueda predecir qué elemento de la la recogida es la primera en ser devuelta en elemento, o que es el siguiente a ser devuelto después de un elemento dado.

Eso no es es lo mismo que decir que no se puede confiar en ella - se puede confiar en si sabes que la colección que estás iterando producirá los resultados en el orden deseado. No es que vaya a elegir elementos al azar. El comportamiento en términos de IEnumerable/IEnumerable<T> está claramente definido en esa página.

Las excepciones más importantes a los ordenamientos predecibles son los diccionarios y los conjuntos, que naturalmente no están ordenados.

Para invertir un IEnumerable<T>, use Enumerable.Reverse - pero si necesita iterar en sentido inverso sobre una colección que está indexada por posición (como una matriz o List<T>), entonces sería más eficiente usar un bucle For que comienza al final y trabaja hacia atrás.

 40
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-04 18:14:53

Tendrías Que hacer algo como:

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

Pero por lo que sé, no puedes hacer un " Para...Cada uno " hacia atrás, aunque eso sería bueno en algunos casos.

 33
Author: SqlRyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-04 17:59:36

Tristemente, los documentos MSDN de on Para Cada establecen que el For Each construct está allí explícitamente para los casos en los que el orden de la iteración no es importante (conjuntos desordenados y similares). Así que desafortunadamente no hay ningún concepto de invertir a Para Cada Uno, ya que el orden no está definido de todos modos.

¡Buena suerte!

 13
Author: Mike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-04 18:00:51

Llame a la System.Linq.Enumerable.Reverse método para obtener un IEnuemrable(Of TSource) en el orden inverso de su fuente enumerable.

 10
Author: Amy B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-11 01:22:38
For Each s As String In myStringList.Reverse
    //' Do stuff here
Next
 3
Author: Tonko Boekhoud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-13 10:16:31

Testig en el marco 4, el código

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

No estaba funcionando, la forma correcta de hacerlo es:

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

Mira: MSDN: Reserve

 3
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-08 10:11:59

La razón por la que no se puede hacer es que, como característica básica de diseño, cada uno puede iterar sobre un enumerable sin un último elemento, o con un último elemento aún desconocido.

 1
Author: reinierpost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-04 18:03:10

Lo que tiene que hacer es crear una matriz con su para cada uno que tenía antes, luego use matriz.invertir y ejecutar el para cada uno en la matriz. Hecho

Salud

 0
Author: xxxmandoxxx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-05 23:24:05

Dependiendo de lo que sucede dentro de su bucle puede hacer un.InsertAt (object, 0) en lugar de an.Agregue y produzca el mismo resultado que una enumeración inversa.

 0
Author: Michael J. Berry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-29 22:03:01

Puede agregar una función extendida a la clase que está tratando de revertir

<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

Entonces lo llamarías así

For Each s As Something In SomeCollection.Reverse

Next
 0
Author: DotNet Programmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-20 19:23:25

Primero debe crear una lista(de cadena) para cada instrucción, y después hacer otra normal para .. paso -1 ..siguiente declaración. ver un ejemplo:

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

Espero que sea útil

 0
Author: Hisham Shaaban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-14 08:10:07

La respuesta aceptada explica por qué, pero para agregar otro ejemplo, para una colección con clave (SortedList, SortedDictionary, Dictionary, etc.) usted puede hacer

For Each Id as Tkey in MyCollection.Keys.Reverse
   // The item in question is now available as MyCollection(Id)
Next
 0
Author: Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-21 09:04:21

' crear una lista de lo que sea y paso a través De Loop Collecting

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

' paso a través de la lista de orden inverso

for each objItem as ToolStripItem in revList   
    ' do whatever (like removing your menu from an ArrayMenu)
next

' reemplazar ToolStripItem y Menú.DropDownItems con lo que necesites

 0
Author: Georg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 17:36:40