Counter in foreach loop in C# -


working of foreach: know,

foreach loop iterates through collection or array 1 one, starting 0 index till last item of collection.

so, if have n items in array.

foreach (var item in arr) {  }   

then, in, 1st iteration, item=arr[0];
then, in 2nd, item=arr[1];
.
.
.
in last (nth), item=arr[n-1];

conclusion: working seems @ each iteration knows value taken array or knows index of item taken array.

now question: how can index of item without using new variable?

foreach (string item in mylist) {    if (item == "myitem")    {        // index of item        break;    } } 

it depends mean "it". iterator knows index it's reached, yes - in case of list<t> or array. there's no general index within ienumerator<t>. whether it's iterating on indexed collection or not implementation. plenty of collections don't support direct indexing.

(in fact, foreach doesn't use iterator @ all. if compile-time type of collection array, compiler iterate on using array[0], array[1] etc. likewise collection can have method called getenumerator() returns type appropriate members, without implementation of ienumerable/ienumerator in sight.)

options maintaining index:

  • use for loop
  • use separate variable
  • use projection projects each item index/value pair, e.g.

     foreach (var x in list.select((value, index) => new { value, index }))  {      // use x.value , x.index in here  } 
  • use smartenumerable class little bit previous option

all first of these options work whether or not collection naturally indexed.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -