【问题标题】:C# DataTable.Rows.Clear() not clearing rows [duplicate]C# DataTable.Rows.Clear() 不清除行[重复]
【发布时间】:2019-03-06 21:52:44
【问题描述】:

我有一个包含许多表的DataSet dsComponents它们都只在内存中,我不将它们与任何数据库同步。有时我需要删除所有行以释放一些内存,但该功能似乎不起作用(基于this answer

if(dsComponents.Tables.Contains("MemoryHistory"))
{
  dsComponents.Tables["MemoryHistory"].Rows.Clear();
}

但如果我在这段代码之后立即中断,则表明表中仍然存在所有行。我也试过了:

if(dsComponents.Tables.Contains("MemoryHistory"))
{
  lock(dsComponents.Tables["MemoryHistory"])
  {
    foreach (DataRow row in dsComponents.Tables["MemoryHistory"].Rows)
    {
      row.Delete();
    }
  }
  dsComponents.Tables["MemoryHistory"].Rows.Clear();
}

这个失败并显示“集合已修改;枚举操作可能无法执行”,即使使用lock。那么,如何清除表中的行但保留表本身(如主键等)?

【问题讨论】:

  • dsComponents.Tables["MemoryHistory"].Rows.Clear() 应该可以正常工作。您确定它正在命中那行代码并且没有其他任何干扰吗?
  • 是的,至少根据 VS 调试器它正在命中。我也在检查行被清除后立即休息
  • 您不能使用foreach 循环然后在循环内向集合中添加/删除元素,因此您可以尝试老式的for 循环,但要倒退,for (int i = dsComponents.Tables["MemoryHistory"].Rows.Count - 1; i >= 0; i--) 和然后在循环内调用dsComponents.Tables["MemoryHistory"].Rows[i].Delete()
  • @jtate 成功了,谢谢

标签: c#


【解决方案1】:

这里的问题是您正在修改 Enumerable,因为您正在迭代它,这是不允许的。

您需要在不迭代行的情况下重置表的行属性。

想想像迭代List<T>

你不会这样做

foreach (var element in list)
{
    list.Remove(element);
}

相反,您会执行以下操作:

list.Clear();

在你的情况下,你会想要做

dsComponents.Tables["MemoryHistory"].Rows.Clear();

我不确定您是否需要锁定对象,但如果您澄清这一点,我很乐意修改我的答案。

【讨论】:

    【解决方案2】:

    就做吧

    dsComponents.Tables["MemoryHistory"].Clear();
    

    【讨论】:

    • 这也将擦除表的主键。我不想再次重新定义约束...
    • 你试过 dsComponents.Tables["MemoryHistory"] = dsComponents.Tables["MemoryHistory"].Clone(); ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 2014-08-10
    • 2013-12-03
    • 2013-06-02
    • 1970-01-01
    • 2022-01-05
    • 2020-11-22
    相关资源
    最近更新 更多