How do you get the index of the current iteration of a foreach loop?

0 votes
asked Sep 4, 2008 by matt-mitchell

Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

For instance, I currently do something like this depending on the circumstances:

int i=0;
foreach (Object o in collection)
    // ...

30 Answers

0 votes
answered Jan 4, 2008 by joseph-daigle

Unless your collection can return the index of the object via some method, the only way is to use a counter like in your example.

However, when working with indexes, the only reasonable answer to the problem is to use a for loop. Anything else introduces code complexity, not to mention time and space complexity.

0 votes
answered Jan 4, 2008 by bryansh

I don't believe there is a way to get the value of the current iteration of a foreach loop. Counting yourself, seems to be the best way.

May I ask, why you would want to know?

It seems that you would most likley be doing one of three things:

1) Getting the object from the collection, but in this case you already have it.

2) Counting the objects for later post processing...the collections have a Count property that you could make use of.

3) Setting a property on the object based on its order in the loop...although you could easily be setting that when you added the object to the collection.

0 votes
answered Jan 4, 2008 by crucible

It's only going to work for a List and not any IEnumerable, but in LINQ there's this:

IList<Object> collection = new List<Object> { 
    new Object(), 
    new Object(), 
    new Object(), 

foreach (Object o in collection)


@Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :)

@Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares.

That said, List might keep an index of each object along with the count.

Jonathan seems to have a better idea, if he would elaborate?

It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable.

0 votes
answered Sep 4, 2008 by flyswat

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

0 votes
answered Sep 4, 2008 by brad-wilson

Could do something like this:

public static class ForEachExtensions
    public static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler)
        int idx = 0;
        foreach (T item in enumerable)
            handler(item, idx++);

public class Example
    public static void Main()
        string[] values = new[] { "foo", "bar", "baz" };

        values.ForEachWithIndex((item, idx) => Console.WriteLine("{0}: {1}", idx, item));
0 votes
answered Sep 16, 2008 by david-b

Literal Answer -- warning, performance may not be as good as just using an int to track the index. At least it is better than using IndexOf.

You just need to use the indexing overload of Select to wrap each item in the collection with an anonymous object that knows the index. This can be done against anything that implements IEnumerable.

System.Collections.IEnumerable collection = Enumerable.Range(100, 10);

foreach (var o in collection.OfType<object>().Select((x, i) => new {x, i}))
    Console.WriteLine("{0} {1}", o.i, o.x);
0 votes
answered Jan 31, 2009 by mat3

Here's a solution I just came up with for this problem

Original code:

int index=0;
foreach (var item in enumerable)
    blah(item, index); // some code that depends on the index

Updated code

enumerable.ForEach((item, index) => blah(item, index));

Extension Method:

    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action)
        var unit = new Unit(); // unit is a new type from the reactive framework ( to represent a void, since in C# you can't return a void
        enumerable.Select((item, i) => 
                action(item, i);
                return unit;

        return pSource;
0 votes
answered Jan 31, 2009 by sachin
int index;
foreach (Object o in collection)
    index = collection.indexOf(o);

This would work for collections supporting IList.

0 votes
answered Sep 25, 2009 by mike-nelson

I disagree with comments that a for loop is a better choice in most cases.

foreach is a useful construct, and not replaceble by a for loop in all circumstances.

For example, if you have a DataReader and loop through all records using a foreach it automatically calls the Dispose method and closes the reader (which can then close the connection automatically). This is therefore safer as it prevents connection leaks even if you forget to close the reader.

(Sure it is good practise to always close readers but the compiler is not going to catch it if you don't - you can't guarantee you have closed all readers but you can make it more likely you won't leak connections by getting in the habit of using foreach.)

There may be other examples of the implicit call of the Dispose method being useful.

0 votes
answered Jan 11, 2010 by ulrichb

My solution for this problem is an extension method WithIndex(),

Use it like

var list = new List<int> { 1, 2, 3, 4, 5, 6 };    

var odd = list.WithIndex().Where(i => (i.Item & 1) == 1);
CollectionAssert.AreEqual(new[] { 0, 2, 4 }, odd.Select(i => i.Index));
CollectionAssert.AreEqual(new[] { 1, 3, 5 }, odd.Select(i => i.Item));
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter