c# - 存储当前行索引的干净实现

标签 c# datatable implementation

我需要从 foreach 循环中找出当前的行索引。

foreach (DataRow row in DataTable[0].Rows)
{
    // I do stuff in here with the row, and if it throws an exception
    // I need to pass out the row Index value to the catch statement
}

try/catch block 中的任何一点都可能发生异常,但是如果我在 foreach 循环中使用增量计数器,并且异常发生在循环,我会得到一个无效的行,因为我已经将指针移动了一个。

我知道我可以在 foreach 范围之外声明一个 DataRow,但是 foreachtry/catch 中 block 。我需要传递行索引,以便在 catch 语句中使用它。我应该说我的 DataTable 是在类级别的范围内。

这真的是获取当前行索引的唯一方法吗?还是有更简洁的实现?

编辑

因此,考虑更多,我可以使用 int 来存储当前行值,并像这样递增该值:

int i = 0;

try
{
    // Some code here - which could throw an exception
    foreach (DataRow row in DataTables[0].Rows)
    {
        // My stuff
        i++;
    }
    // Some code here - which could throw an exception
}
catch
{
    // Use the counter
    DataRow row = DataTables[0].Rows[i];
}

但是,如果foreach 没有抛出异常,那么i 的值将大于表中的实际行数。显然,我可以在 foreach 循环之后执行 i--;,但这似乎是一个真的肮脏的 hack。

最佳答案

一种肮脏的方法是将它包装在一个额外的 trycatch block 中:

int i = 0;
try
{
    // Some code here - which could throw an exception

    try{
        foreach (DataRow row in DataTables[0].Rows)
        {
            // My stuff
            i++;
        }
        // Some code here - which could throw an exception
    }
    catch{
      i--;
      throw;
    }

}
catch
{
    // Use the counter
    DataRow row = DataTables[0].Rows[i];
}

这样你肯定知道异常是在 foreach 之后或期间抛出的,你总是得到正确的迭代器。

关于c# - 存储当前行索引的干净实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9017240/

相关文章:

c# - 堆栈跟踪中的错误行号

java - 用数据填充 primefaces 数据表

javascript - jquery 中的数据表不实时刷新数据

c# - 接口(interface)继承一致性

c# - 简单的 C# 正则表达式问题

c# - 播放文件中的nAudio奇数缓冲区值

c++ - 链表复制构造函数实现细节

java - 如何将泛型接口(interface)实现为非泛型类 Java

c# - 选择 List<int> 中所有值的位置

javascript - 左固定列与表 colspan