简体   繁体   English

循环遍历数据表并删除行

[英]Looping through a datatable and remove row

I have populated a Datatable, from 2 different servers. 我已经从2个不同的服务器填充了一个Datatable。 I am able to make adjustments where my length>0, what I want to do is remove the rows that does not hit. 我可以在我的长度> 0的地方进行调整,我想要做的是删除未击中的行。 Here is a summary of what I have 以下是我所拥有的内容摘要

DataRow[] dr = payments.dtPayments.Select(myselect);

if (dr.Length > 0)
{
   for (int a = 0; a < dr.Length; a++)
   {
      if (thisOption == true)
         dr[0].Delete();
      else if (otherOption == true)
      {
         dr[0]["Date"] = myDataReader["date"].ToString().Trim();
         dr[0]["Pay"] = payTypeName(myDataReader["ccdsrc"].ToString()
                                                          .Trim());
      }
   }
}
if (dr.Length == 0)
{                        
   if (LastOption == true)
   {
     //DataRow should be removed
   }                        
}

I'm not sure I completely understand your question but it seems that you try to remove an entry from the collection while you are still looping over it. 我不确定我是否完全理解你的问题,但是当你还在循环时,你似乎试图从集合中删除一个条目。 (which will cause an array index error) (这会导致数组索引错误)

You should save a reference to each entry you want to delete in a new collection and then remove all the new entries from the old collection: 您应该在新集合中保存对要删除的每个条目的引用,然后从旧集合中删除所有新条目:

DataRow[] dr = payments.dtPayments.Select(myselect);
List<DataRow> rowsToRemove = new List<DataRow>();

for (int a = 0; a < dr.Length; a++) {
    if(/* You want to delete this row */) {
        rowsToRemove.Add(dr[a]);
    }
}

foreach(var dr in rowsToRemove) {
    payments.dtPayments.Rows.Remove(dr);
}

If dr.Length is zero, then your select did not return any rows. 如果dr.Length为零,那么您的选择不会返回任何行。 If you want to delete rows that don't match your criteria, then I would implement that as a different type of query. 如果要删除与您的条件不匹配的行,那么我会将其实现为不同类型的查询。 It could also be that I am completely misunderstanding your question. 也可能是我完全误解了你的问题。 Could you update your question to show your SQL and indicate where in the code sample you are having the problem: inside the loop or after the loop where you have your comment? 您是否可以更新您的问题以显示您的SQL并指出代码示例中您遇到问题的位置:在循环内或循环之后您有注释?

You need to create a datarow outside the loop, then when you get to the row you want to remove assign it to the row you created outside. 您需要在循环外创建一个数据行,然后当您到达要删除的行时,将其分配给您在外部创建的行。 and break the loop. 并打破循环。 Then below the loop you can remove it. 然后在循环下面你可以删除它。

DataRow r = null;
foreach(DataRow row in table.Rows)
{
   if(condition==true)
   {
      r = row;
      break;
   }
}

table.Rows.Remove(r);

Have you tryed this? 你试过这个吗?

payments.dtPayments.Rows.Remove(dr) payments.dtPayments.Rows.Remove(DR)

您可以反向循环遍历集合(对于(int i = rows.length-1; x> -1; x--))以删除多行,以确保您不会获得索引超出绑定的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM