-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.
My question is: Why???? If you want Count you don’t need any foreach, just take the
Count
of your list..– Leandro Angelo
@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.
– Samuel Renan Gonçalves Vaz
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.– LeonanCarvalho
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 anyforeach
manually made for a collection of your– Jefferson Quesado
@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.– Maniero
@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.
– Samuel Renan Gonçalves Vaz
@All right then, but I think I could do better than that.
– Maniero