Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Know This is the Last Iteration of a Loop?

Tags:

c#

list

generics

Is there a fancy way to know you are in the last loop in a List without using counters

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?
}
like image 677
Terco Avatar asked Apr 27 '11 17:04

Terco


2 Answers

No, you will have to use a regular for(int i=0; i<myList.Length; i++) { ... } loop for that.

like image 173
Elian Ebbing Avatar answered Oct 08 '22 12:10

Elian Ebbing


How about using a for loop instead?

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 is useful - but if you need to keep count of what you are doing, or index things by count, then just revert to a good old for loop.

like image 38
Rob Levine Avatar answered Oct 08 '22 14:10

Rob Levine