2011-04-27 11 views
6

¿Hay una manera de lujo de saber que estás en el último bucle en una lista sin utilizar contadoresCómo saber Esta es la última iteración de un bucle?

List<string> myList = new List<string>() {"are", "we", "there", "yet"}; 

foreach(string myString in myList) { 
    // Is there a fancy way to find out here if this is the last time through? 
} 
+1

lo que estás tratando de hacer hasta el último elemento? ¿Estás tratando de construir una oración y agregar puntuación al final? Si es así, podría intentar 'string.Join (" ", myList.ToArray()) +". "' – hunter

+0

encontró una solución para usted waaaaaay en la parte inferior ... – hunter

Respuesta

8

No, usted tendrá que utilizar un bucle for(int i=0; i<myList.Length; i++) { ... } regular para eso.

+1

Gracias, esta fue mi retroceso, pero yo quería asegúrese de no perderme nada primero. – Terco

0

No, no lo es, usted tiene que utilizar un contador si desea utilizar foreach.

1

No hay una manera eficiente de hacerlo.

Simplemente use un for lazo e índice. Funciona más rápido de cualquier manera.

0

Uso for operador en lugar de foreach

4

¿Qué le parece usar un bucle for?

List<string> myList = new List<string>() {"are", "we", "there", "yet"}; 

for (var i=0; i<myList.Count; i++) 
{ 
    var myString = myList[i]; 
    if (i==myList.Count-1) 
    { 
     // this is the last item in the list 
    } 
} 

foreach es útil - pero si usted necesita para llevar la cuenta de lo que está haciendo, o cosas por el índice de recuento, a continuación, sólo volver a una buena edad for bucle.

0

Bueno ... no hay forma de saber eso. No es tan fácil como podría suponer. La estructura de datos de la lista es solo una forma de pedir elementos uno tras otro. Pero no tiene forma de decir si un artículo es el último elemento simplemente usando la estructura foreach. El mejor uso para la estructura con la propiedad count para saber si pulsas el último elemento (o anterior).

var length = list.Count; 

for (var idx = 0; idx < list.Count; idx++) 
{ 
    if (idx == (length - 1)) 
    { 
     // The last item. Do something 
    } 
} 

Espero que ayude.

3

Hay dos maneras en que lo haría.

En primer lugar, con un bucle en lugar de forforeach

for(int i = 0; i < myList.Count; i++) 
{ 
    string myString = myList[i]; 
    bool isLast = i == myList.Count - 1; 

    ... 
} 

O, si esto tiene que trabajar con los encuestadores, cambiar el orden de las cosas. Normalmente MoveNext se realiza como el control del ciclo while, pero si lo hacemos justo al comienzo del ciclo, podemos usar su retorno para determinar si estamos al final de la lista o no.

IEnumerator<string> enumerator = myList.GetEnumerator(); 
bool isLast = !enumerator.MoveNext(); 
while(!isLast) 
{ 
    string myString = enumerator.Current; 
    isLast = !enumerator.MoveNext(); 

    ... 
} 
0

La manera "elegante" es mantener 1 elemento de búsqueda anticipada, pero ¿por qué querría hacerlo? Jus mantener un conteo. Aquí está la manera elegante. Sin contadores, sin verificar la propiedad Count. Todo lo que utiliza es un enumerador:

using System; 
using System.Collections.Generic; 

namespace Sandbox 
{ 
    class Program 
    { 

    enum ListPosition : byte 
    { 
     First  = 0x01  , 
     Only  = First|Last , 
     Middle = 0x02  , 
     Last  = 0x04  , 
     Exhausted = 0x00  , 
    } 

    private static void WalkList(List<int> numbers) 
    { 
     List<int>.Enumerator numberWalker = numbers.GetEnumerator(); 
     bool     currFetched = numberWalker.MoveNext(); 
     int     currValue = currFetched ? numberWalker.Current : default(int); 
     bool     nextFetched = numberWalker.MoveNext(); 
     int     nextValue = nextFetched ? numberWalker.Current : default(int); 
     ListPosition   position  ; 

     if  ( currFetched && nextFetched) position = ListPosition.First  ; 
     else if ( currFetched && ! nextFetched) position = ListPosition.Only  ; 
     else if (! currFetched     ) position = ListPosition.Exhausted ; 
     else throw new InvalidOperationException("Reached Unreachable Code. Hmmm...that doesn't seem quite right"); 

     while (position != ListPosition.Exhausted) 
     { 
     string article = (position==ListPosition.Middle?"a":"the"); 

     Console.WriteLine(" {0} is {1} {2} item in the list" , currValue , article , position); 

     currFetched = nextFetched ; 
     currValue = nextValue ; 

     nextFetched = numberWalker.MoveNext()       ; 
     nextValue = nextFetched?numberWalker.Current:default(int) ; 

     if  ( currFetched && nextFetched) position = ListPosition.Middle ; 
     else if ( currFetched && ! nextFetched) position = ListPosition.Last  ; 
     else if (! currFetched     ) position = ListPosition.Exhausted ; 
     else throw new InvalidOperationException("Reached Unreachable Code. Hmmm...that doesn't seem quite right"); 

     } 

     Console.WriteLine() ; 
     return ; 
    } 

    static void Main(string[] args) 
    { 
     List<int> list1 = new List<int>(new []{ 1 ,    }) ; 
     List<int> list2 = new List<int>(new []{ 1 , 2 ,   }) ; 
     List<int> list3 = new List<int>(new []{ 1 , 2 , 3 ,  }) ; 
     List<int> list4 = new List<int>(new []{ 1 , 2 , 3 , 4 , }) ; 

     Console.WriteLine("List 1:") ; WalkList(list1) ; 
     Console.WriteLine("List 2:") ; WalkList(list2) ; 
     Console.WriteLine("List 3:") ; WalkList(list3) ; 
     Console.WriteLine("List 4:") ; WalkList(list4) ; 

     return ; 
    } 

    } 
} 
0

Depende de su definición de "fantasía". Esto podría calificar:

if (myList.Count > 0) 
{ 
    myList.Take(myList.Count - 1)).ForEach(myString => doSomething(myString)); 
    doSomethingElse(myList.Last()); 
} 

Para mí, eso parece cercano a lo que estás buscando. Tenga en cuenta que no es súper alto rendimiento, pero es corto y bastante legible, al menos para mí.También puede escribir de esta manera:

if (myList.Count > 0) 
{ 
    foreach (string myString in myList.Take(myList.Count - 1)) 
    { 
     doSomething(myString); 
    } 

    doSomethingElse(myList.Last()); 
} 

Aquí es otra alternativa, que yo consideraría la más obvia, pero es probablemente la manera más rápida de hacer esto:

if (myList.Count > 0) 
{ 
    for (int i = 0; i < myList.Count - 1; i++) 
    { 
     doSomething(myList[i]); 
    } 

    doSomethingElse(myList.Count - 1); 
} 
Cuestiones relacionadas