How to tell if foreach is traversing the last item in the list [duplicate]

-1

I've created an application in console and a foreach to scroll through my list of integers:

var lista = new List<int>() { 2, 6, 1, 4, 20, 21};

int count = 0;
foreach (var item in lista)
{
   count++;

   //if(???)
       //count = 0;

   //....
}

Console.ReadKey();

How do I know if my foreach is in the last item on my list?

Well, if it's going through the last element, inside the if will zero my count variable.

    
asked by anonymous 05.02.2018 / 14:16

1 answer

2

You probably need something better, but you can not know without more detail in the question.

What you ask is this

void Main()
{
    var lista = new List<int>() { 2, 6, 1, 4, 20, 21};

    int count = 0;
    foreach (var item in lista)
    {
        count++;        
        Console.WriteLine(count);

        if(count == lista.Count) {
           count = 0;   
           Console.WriteLine("último");
        }          
    }
}
    
05.02.2018 / 14:27