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

If you can use Linq, you can do it this way:

foreach (var pair in temptable.Rows.Cast<DataRow>()
                                   .Select((r, i) => new {Row = r, Index = i}))
{
    int index = pair.Index;
    DataRow row = pair.Row;
}

I have a type in MiscUtil which can help with this - SmartEnumerable. It's a dumb name, but it works :) See the usage page for details, and if you're using C# 3 you can make it even simpler:

foreach (var item in temptable.Rows.AsSmartEnumerable())
{
    int index = item.Index;
    DataRow value = item.Value;
    bool isFirst = item.IsFirst;
    bool isLast = item.IsLast;
}

You have to create one yourself

var i = 0;
foreach (DataRow temprow in temptable.Rows)
{
    this.text = i;
    // etc
    i++;
}

or you can just do a for loop instead.


You actually Don't. One of the beauties with foreach is that you don't have the extra set of code handling incrementing and checks on the length.

If you want to have your own Index you would have to do something like this

int rowindex = 0;
foreach (DataRow temprow in temptable.Rows)
{
//this.text = temprow.INDEX????
    this.text = rowindex++;
}

Tags:

C#

Foreach