数据表+使用循环删除c#中的一行

时间:2010-06-30 14:29:22

标签: c# asp.net datatable

我有一个数据表,我想在这里删除一行是我的代码它给我一个异常

foreach (DataRow row in dt1.Rows)
{
    if ((row["Name"] == "Select a Lookbook") || (row["Name"] == "Create a new Lookbook"))
    {
        row.Delete();
        dt1.AcceptChanges();
    }
}

我甚至在if语句之外尝试过,在forloop之外仍然会抛出错误任何想法如何实现此任务这是我得到的例外:

Collection was modified; enumeration operation might not execute.

最终工作代码:

foreach (DataRow row in dt1.Select())
{
    if ((row["Name"] == "Select a Lookbook") ||    (row["Name"] == "Create a new Lookbook"))
    {
        row.Delete();                                       
    }

}

3 个答案:

答案 0 :(得分:17)

不使用dt1.Rows,而是使用dt1.Select()

这里的目标不是使用集合本身,而是使用不是Rows集合的行数组

答案 1 :(得分:9)

在迭代DataTable.Rows时创建要删除的行列表,然后单独删除它们。

非LINQ解决方案:

List<DataRow> rowsToDelete = new List<DataRow>();
foreach (DataRow row in dt1.Rows)
{
    if ((row["Name"] == "Select a Lookbook") || 
        (row["Name"] == "Create a new Lookbook"))
    {
        rowsToDelete.Add(row);
    }
}
foreach (DataRow row in rowsToDelete)
{
    row.Delete();
}
dt1.AcceptChanges();

LINQ解决方案:

List<DataRow> rowsToDelete = dt1.Rows.AsEnumerable()
    .Where(row => (row["Name"] == "Select a Lookbook") || 
                  (row["Name"] == "Create a new Lookbook"))
    .Tolist();
foreach (DataRow row in rowsToDelete)
{
    row.Delete();
}
dt1.AcceptChanges();

答案 2 :(得分:1)

当我遇到这个问题时,我就是这样做的。

            Dim index As Integer = 0
            Dim count As Integer = resultsDT.Rows.Count - 1
            For i As Integer = 0 To count
                If resultsDT.Rows(index).Item("something") = "something" Then
                    resultsDT.Rows(index).Delete()
                    resultsDT.AcceptChanges()
                    index = index - 1
                End If

                index = index + 1
                i = i + 1
            Next