是否建议在Foreach循环中从DataTable中删除Row?

时间:2012-02-26 07:31:05

标签: c# datatable datarow

如标题所示,是否建议在foreach循环中从数据表中删除数据行?

这是我到目前为止所得到的 -

            foreach (DataRow row in dt.Rows)
            {
                billObj.callerID = Convert.ToInt64(row["callerID"]);
                billObj.bsRespond = billObj.chargePhone(billObj);
                if (!billObj.bsRespond.StartsWith("OK"))
                {
                    dt.Rows.Remove(row);
                }
            }

3 个答案:

答案 0 :(得分:3)

当然不是,你正在修改你正在迭代的集合。当您尝试删除那里的行时,您的程序会爆炸。使用为其创建的枚举器otherwise it will throw an InvalidOperationException()时,无法修改集合。

答案 1 :(得分:1)

为什么不使用另一个枚举器?

foreach (DataRow row in dt.Rows.Cast<DataRow>().ToArray())
{

...

}

答案 2 :(得分:0)

如果没有“RemoveAll(谓词)”,通常的方法是保留一个删除列表(这里推广到任何类型):

var remove = new List<SomeType>();
foreach(var row in source) {
    if(condition) remove.Add(row);
}
foreach(var obj in remove) {
    source.Remove(obj);
}

但是,如果可用,则:

source.RemoveAll(row => condition);

方法更简单。