Skip to main content
 首页 » 编程设计

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

2024年02月23日14lvdongjie

我在尝试从 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); 
  } 
}