[英]Remove row from generic datatable in 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网站没有多大帮助。
谢谢!
您的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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.