You cannot, because IEnumerable has no index at all ... if you are sure that your counter has fewer int.MaxValue elements (or long.MaxValue if you use the long index), you can:
Do not use foreach and use a for loop, converting your IEnumerable to a common total score:
var genericList = list.Cast<object>(); for(int i = 0; i < genericList.Count(); ++i) { var row = genericList.ElementAt(i); }
Have an external index:
int i = 0; foreach(var row in list) { ++i; }
Get index through Linq:
foreach(var rowObject in list.Cast<object>().Select((r, i) => new {Row=r, Index=i})) { var row = rowObject.Row; var i = rowObject.Index; }
In your case, since your IEnumerable not generic, I prefer to use foreach with an external index (second method) ... otherwise you can Cast<object> outside your own to convert it to IEnumerable<object> .
Your data type is not clear from the question, but I am assuming object , as it is the source of the elements (it may be a DataGridRow ) ... you can check if it is directly converted to a general IEnumerable<object> without calling Cast<object>() , but I will not make such assumptions.
All this said:
The concept of "index" does not matter for IEnumerable . IEnumerable can be potentially infinite. In your example, you are using an ItemsSource for a DataGrid , so it is more likely that your IEnumerable is just a list of objects (or DataRows ) with a finite number (and hopefully fewer int.MaxValue ) members, but IEnumerable can represent anything that can be listed ( and the listing could never end).
Take this example:
public static IEnumerable InfiniteEnumerable() { var rnd = new Random(); while(true) { yield return rnd.Next(); } }
So, if you do:
foreach(var row in InfiniteEnumerable()) { }
Your foreach will be infinite: if you used the int (or long ) index, you will eventually overflow it (and if you do not use the unchecked context, it will throw an exception if you continue to add to it: even if you used unchecked , the index would also be pointless ... at some point - when it overflows - the index would be the same for two different values).
So, although the above examples work for typical use, I would prefer not to use the index at all if you can avoid it.
source share