How to know if foreach is going through the last item on the list

Asked

Viewed 446 times

-1

I created an application in console and a foreach to go 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 to know if my foreach is on the last item on my list?

For if it is running through the last element, within if I will reset my Count variable.

  • 4

    My question is: Why???? If you want Count you don’t need any foreach, just take the Count of your list..

  • @Leandroangelo It is that this Count when it is the last element of my list it has to be zeroed, so I put //... because it has more implementation that I did not find necessary to put.

  • if your Count (call it i, j, x, "pebble what", not to be confused) is equal to Count from your list you will be at the end.

  • If you are in an environment where the list is not changed during the iteration, then the foreach of the standard library collections will go through all the elements yes (that’s your case). PERHAPS fail in the case of any foreach manually made for a collection of your

  • @samuelrvg could put what he wants to do inside the loop and the if? There’s probably a way to make this code much better.

  • @I might even put Maniero, but in this case it would be more complex to explain how it’s working, because I’m using an array inside that loop to send commands to a scale module, I am working with protocol Modbus and the library I use to send these commands accepts an array to send, the loop is precisely to create multiple commands and send these commands as a specific table I have... but anyway, thanks for your attention.

  • 1

    @All right then, but I think I could do better than that.

Show 2 more comments

1 answer

2


You probably need something better, but there’s no way to know without further details 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");
        }          
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.