Foreach loop

  • Thread starter Thread starter Robert Bravery
  • Start date Start date
R

Robert Bravery

HI all,

If I have a foreach loop, is there a way to tell what number of itteration I
am on during each loop

Thanks
Robert
 
Robert said:
HI all,

If I have a foreach loop, is there a way to tell what number of itteration I
am on during each loop

Thanks
Robert

The way the I would do it is have a variable that is incremented at the
end of the loop. They are probably other ways to do it though.
 
Hi,
Thats what I have at the moment. I thought there might have been a more
elegant way of doing it

Thanks
Robert
 
Not without an auxiliary variable. Foreach relies on iterators, and
the concept of .NET iterators doesn't include an iteration count.
 
Hello Robert,

Realization of foreach based on the IEnumerable/IEnumerator interfaces which
don't have members to get the number of the current iteration

You can check this interfaces in MSDN


RB> Hi,
RB> Thats what I have at the moment. I thought there might have been a
RB> more
RB> elegant way of doing it
RB> Thanks
RB> Robert
RB> RB>RB> itteration I
RB>---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
It depends on the type you are dealing with.

foreach in the case of an array is special cased and will give you identical
code to a for loop.

Cheers,

Greg
 
Not really .. if you are dealing with an array _don't_ use foreach if you
need a count as it produces the exact same thing as a for (including having
a counter) its just that you can't access it. Adding "your own counter" will
actually maintain 2 counters which is rather inefficient.

Cheers,

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Collections ByVal ByRef? 4
simple way of continuing out of outter loop 4
about Collections 1
Last row in foreach loop 37
Foreach Loop. Distinct 8
threading 6
defining variable in loop 2
Find Ints in List ... 4

Back
Top