Alex Rivera | Logout

How can I know a row index while iterating with foreach?

Asked 2009-10-08T22:14:10.083
11

in the next example how can I know the current row index?

foreach (DataRow temprow in temptable.Rows)
{
//this.text = temprow.INDEX????
}
Edit
Report

1 Answer

1

It's not possible with a standard foreach loop. The simplest way is to use a for loop

for ( int i = 0; i < temptable.Rows.Count; i++ ) {
  DataRow temprow = (DataRow)temptable.Rows[i];
  ...
}

Another option is to use an extension method

public static void ForEachIndex<T>(this IEnumerable<T> e, Action<T,int> del) {
  var i = 0; 
  foreach ( var cur in e ) {
    del(cur,i);
  }
}

...

temptable.Rows.Cast<DataRow>.ForEachIndex((cur,index) 
{
  ...
});
answered 2009-10-08T22:17:01.567

Your Answer