2011-06-01 12 views

Respuesta

6

Debe realizar un seguimiento de un contador y luego verificar el último elemento:

int i = 1; 
foreach (Object element in elements.under) 
{ 
    if (i == elements.under.Count) //Use count or length as supported by your collection 
    { 
     //last element 
    } 
    else 
    { i++; } 
} 
+0

funciona. Pero ¿por qué -1? :) – markzzz

+0

@markzz - lo eliminé hace mucho tiempo. si tu i comienza con 0, necesitarás -1, de lo contrario ignorarás. –

3

esta respuesta en lo que puede resolver el problema que desea tener mirada a ella

How do you find the last loop in a For Each (VB.NET)?

También puedes ver esta biblioteca Enumerating with extra info in the Miscellaneous Utility Library

foreach (SmartEnumerable<string>.Entry entry in 
       new SmartEnumerable<string>(list)) 
     { 
      Console.WriteLine ("{0,-7} {1} ({2}) {3}", 
           entry.IsLast ? "Last ->" : "", 
           entry.Value, 
           entry.Index, 
           entry.IsFirst ? "<- First" : ""); 
     } 

código basado en enlace anterior biblioteca

4
foreach (Object element in elements.under) 
    { 
     if (element == elements.under.Last()) 
     { 
      //Print Code 
     } 
     else 
     { 
      //Do other thing here 
     } 
    } 
Cuestiones relacionadas