从 C# 中的通用数据表中删除行

发布于 2024-10-07 19:41:47 字数 664 浏览 0 评论 0原文

我在尝试从 C# 数据表中删除行时遇到了问题。问题是数据表是从 SQL 构建的,因此它可以有任意数量的列,并且可能有也可能没有主键。因此,我无法根据特定列中的值或主键删除行。

这是我正在做的事情的基本概述:

//Set up a new datatable that is an exact copy of the datatable from the SQL table.  
newData = data.Copy();
//...(do other things)
foreach (DataRow dr in data.Rows)
{
  //...(do other things)
  // Check if the row is already in a data copy log.  If so, we don't want it in the new datatable.
  if (_DataCopyLogMaintenance.ContainedInDataCopyLog(dr))
  {
    newData.Rows.Remove(dr);
  }
}

但是,这给了我一条错误消息,“给定的 DataRow 不在当前的 DataRowCollection 中”。鉴于 newData 是数据的直接副本,这没有任何意义。还有其他人有什么建议吗? MSDN 网站没有多大帮助。

谢谢!

I ran into a problem trying to remove a row from a datatable in C#. The problem is that the datatable is built from SQL, so it can have any number of columns and may or may not have a primary key. So, I can't remove a row based on a value in a certain column or on a primary key.

Here's the basic outline of what I'm doing:

//Set up a new datatable that is an exact copy of the datatable from the SQL table.  
newData = data.Copy();
//...(do other things)
foreach (DataRow dr in data.Rows)
{
  //...(do other things)
  // Check if the row is already in a data copy log.  If so, we don't want it in the new datatable.
  if (_DataCopyLogMaintenance.ContainedInDataCopyLog(dr))
  {
    newData.Rows.Remove(dr);
  }
}

But, that gives me an error message, "The given DataRow is not in the current DataRowCollection". Which doesn't make any sense, given that newData is a direct copy of data. Does anyone else have any suggestions? The MSDN site wasn't much help.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画骨成沙 2024-10-14 19:41:47

您的 foreach 需要位于副本上,而不是原始集合上。您无法从collection2 中删除collection1 中包含的对象。

foreach (DataRow dr in newData.Rows)

否则,您可以使用计数器来删除索引。像这样的东西:

for(int i = 0; i < data.Rows.Count; i++)
{
  if (_DataCopyLogMaintenance.ContainedInDataCopyLog(data.Rows[i]))
  {
    newData.Rows.RemoveAt(i);
  }
}

Your foreach needs to be on the copy, not the original set. You cannot remove an object contained in collection1 from collection2.

foreach (DataRow dr in newData.Rows)

Otherwise you could use a counter to remove at an index. Something like this:

for(int i = 0; i < data.Rows.Count; i++)
{
  if (_DataCopyLogMaintenance.ContainedInDataCopyLog(data.Rows[i]))
  {
    newData.Rows.RemoveAt(i);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文