Counter in foreach loop in C#
It depends what you mean by "it". The iterator knows what index it's reached, yes - in the case of a List<T>
or an array. But there's no general index within IEnumerator<T>
. Whether it's iterating over an indexed collection or not is up to the implementation. Plenty of collections don't support direct indexing.
(In fact, foreach
doesn't always use an iterator at all. If the compile-time type of the collection is an array, the compiler will iterate over it using array[0]
, array[1]
etc. Likewise the collection can have a method called GetEnumerator()
which returns a type with the appropriate members, but without any implementation of IEnumerable
/IEnumerator
in sight.)
Options for maintaining an index:
- Use a
for
loop - Use a separate variable
Use a projection which projects each item to an index/value pair, e.g.
foreach (var x in list.Select((value, index) => new { value, index })) { // Use x.value and x.index in here }
Use my
SmartEnumerable
class which is a little bit like the previous option
All but the first of these options will work whether or not the collection is naturally indexed.
Use for
instead of foreach
. foreach
doesn't expose its inner workings, it enumerates anything that is IEnumerable
(which doesn't have to have an index at all).
for (int i=0; i<arr.Length; i++)
{
...
}
Besides, if what you're trying to do is find the index of a particular item in the list, you don't have to iterate it at all by yourself. Use Array.IndexOf(item)
instead.
Your understanding of foreach
is incomplete.
It works with any type that exposes IEnumerable
(or implements a GetEnumerable
method) and uses the returned IEnumerator
to iterate over the items in the collection.
How the Enumerator
does this (using an index, yield
statement or magic) is an implementation detail.
In order to achieve what you want, you should use a for
loop:
for (int i = 0; i < mylist.Count; i++)
{
}
Note:
Getting the number of items in a list is slightly different depending on the type of list
For Collections: Use Count [property]
For Arrays: Use Length [property]
For IEnumerable: Use Count() [Linq method]