Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter in foreach loop in C#

Working of foreach: As I know,

foreach is a loop which iterates through a collection or array one by one, starting from 0 index till the last item of the collection.

So, if I have n items in an 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: from working it seems that at each iteration it knows that which value to be taken from array or it knows the index of the item to be taken from array.

Now my question: How can I get index of an item without using a new variable?

foreach (string item in mylist) {    if (item == "myitem")    {        // get index of item        break;    } } 
like image 842
Javed Akram Avatar asked Dec 02 '10 17:12

Javed Akram


People also ask

How do I add a counter in foreach loop?

Define an integer outside of the loop, and increment it inside of your loop. Use a for loop instead of foreach, which has a count for you: for(int i = 0; i < array. length; i++) { var item = array[i]; Console.

How do you count in foreach?

foreach is a php construct, and doesn't have any items - arrays do. using count($array) returns the number of elements in it.

What is index in foreach?

Luckily, there are several ways to get an index variable with foreach : Declare an integer variable before the loop, and then increase that one inside the loop with each loop cycle. Create a tuple that returns both the element's value and its index. Or swap the foreach loop with the for loop.

Which object can be iterated in foreach loop in C#?

Generally, in c# Foreach loop will work with the collection objects such as an array, list, etc., to execute the block of statements for each element in the array or collection.


2 Answers

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.

like image 105
Jon Skeet Avatar answered Sep 18 '22 20:09

Jon Skeet


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.

like image 39
Yodan Tauber Avatar answered Sep 19 '22 20:09

Yodan Tauber