If all you know is that the collection is an IEnumerable, but need to keep track of how many elements you have processed so far (and thus the total when you're done), you can add a couple lines to a basic for loop:
var coll = GetMyCollectionAsAnIEnumerable();
var idx = 0;
for(var e = coll.GetEnumerator(); e.MoveNext(); idx++)
{
var elem = e.Current;
//use elem and idx as you please
}
You can also add an incremented index variable to a foreach:
var i=0;
foreach(var elem in coll)
{
//do your thing, then...
i++;
}
If you want to make this look more elegant, you can define an extension method or two to "hide" these details:
public static void ForEach<T>(this IEnumerable<T> input, Action<T> action)
{
foreach(T elem in input)
action(elem);
}
public static void ForEach<T>(this IEnumerable<T> input, Action<T, int> action)
{
var idx = 0;
foreach(T elem in input)
action(elem, idx++); //post-increment happens after parameter-passing
}
//usage of the index-supporting method
coll.ForEach((e, i)=>Console.WriteLine("Element " + (i+1) + ": " + e.ToString()));
for ()
loop.