从 C# 中的通用数据表中删除行
我在尝试从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
foreach
需要位于副本上,而不是原始集合上。您无法从collection2 中删除collection1 中包含的对象。否则,您可以使用计数器来删除索引。像这样的东西:
Your
foreach
needs to be on the copy, not the original set. You cannot remove an object contained in collection1 from collection2.Otherwise you could use a counter to remove at an index. Something like this: