如何使用C#比较和删除数据表行: [英] How To Compare and delete datatable row using C#:

查看:61
本文介绍了如何使用C#比较和删除数据表行:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,如DTTable1和DTTable2。它有以下记录。



DTTable1:

I have two tables such as DTTable1 and DTTable2. It has the following records.

DTTable1:

 ItemID     Specification    Amount
---------  ---------------  ---------
   1             A             10
   1             B             20
   1             C             30





DTTable1:



DTTable1:

 ItemID     Specification    Amount
---------  ---------------  ---------
   1             A             10
   1             B             20
   1             C             30
   2             A             10
   2             B             20
   3             A             10
   3             B             20



这里我想比较这两个表。如果DTTable1记录存在于DTTable2中(仅考虑ItemID),则删除ItemID与DTTable1相同的相应行。



我尝试过以下代码,但无法解决问题。





代码片段1:


Here I want to compare these two tables. If DTTable1 records present in DTTable2(consider only ItemID) then remove the corresponding rows which has the ItemID same as DTTable1.

I have tried following codes but cant solve the problem.


Code snippet 1:

foreach (DataRow DR in DTTable2.Rows)
{
   if (DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
   {
        DTTable2.Rows.Remove(DR);
   }
}
DTTable2.AcceptChanges();



它显示错误,收集已被修改;枚举操作可能无法执行。所以我使用For Loop,它也没有给出预期的结果。





代码片段2:


It showed the error, "Collection was modified; enumeration operation might not execute". So I used For Loop, It also not given the desired result.


Code Snippet 2:

for (int i = 0; i < DTTable2.Rows.Count; i++)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
    {
        DTTable2.Rows.RemoveAt(i);
    }
}
DTTable2.AcceptChanges();







Code Snippet 3:




Code Snippet 3:

List<datarow> rowsToDelete = new List<datarow>();
foreach (DataRow DR in DTTable2.Rows)
{
    if (DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        rowsToDelete.Add(DR);           
}

foreach (var r in rowsToDelete)
    DTTable2.Rows.Remove(r);







代码片段4:




Code Snippet 4:

DTTable2.Rows
    .Where(DR => DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
    .ToList()
    .ForEach(r => DTTable2.Rows.Remove(r));







代码片段5:




Code Snippet 5:

for (int i = DTTable2.Rows.Count - 1; i >= 0; i--)
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);







代码段6:




Code Snippet 6:

int i = 0;
while (i < DTTable2.Rows.Count)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);
    else
        i++;
}







Code Snippet 7:




Code Snippet 7:

var list = DTTable2.Rows.ToList();//create new list of rows
foreach (DataRow DR in list)
{
    //if bla bla bla
    DTTable2.Rows.Remove(DR);
}







Code Snippet 8:




Code Snippet 8:

var result =  DTTable1.AsEnumerable()
                   .Where(row => !DTTable2.AsEnumerable()
                                         .Select(r => r.Field<int>("ItemID"))
                                         .Any(x => x == row.Field<int>("ItemID"))
                  ).CopyToDataTable();





代码片段9:





Code snippet 9:

for (int i = 0; i < DTTable2.Rows.Count; i++)
{
   if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[i]["ItemID"].ToString())
   {
      cmd = new SqlCommand("DELETE FROM DetailsTB WHERE ItemID = '" + DTTable2.Rows[i]["ItemID"].ToString() + "' ", con1);
      cmd.ExecuteNonQuery();
   }
}







但有时,第二行不会从表中删除。我得到了最终的DataTable




But sometimes, the second row doesn't remove from the table. I get the final DataTable as

 ItemID     Specification    Amount
---------  ---------------  ---------
   1             B             20
   2             A             10
   2             B             20
   3             A             10
   3             B             20



如何解决这个问题?最简单的方法是什么?

以上所有代码都无法正常工作。

某些数据不会从DTTable2中删除,也与DTTable1相匹配。

这些只是我写的很少的方法,但我尝试了20多个方法来做同样的事情。


How to solve this? What is the simplest method to do this?
All above code cant work.
some data are not deleted from DTTable2 that are also match with DTTable1.
These are only Few method here I write but i tried more than 20 method to do the same.

推荐答案

在你的代码snipet 6中:

in your code snipet 6:
Code Snippet 6:
 Collapse | Copy Code
int i = 0;
while (i < DTTable2.Rows.Count)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);
    else
        i++;
}





试试



代码片段6:



try

Code Snippet 6:

for (int i=DTTable2.Rows.Count-1;i>=0;i--)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);
    else
        i++;
}





这可能会给你带来成功



this might give you success


试试这段代码..



try this code..

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace console_poc
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable DTTable1 = new DataTable();
            DTTable1.Columns.Add("ItemID", typeof(int));
            for (int i = 0; i <= 5; i++)   
                            DTTable1.Rows.Add(i);  // table 1 contains { 0,1,2,3,4,5,7}

            DataTable DTTable2 = new DataTable();
            DTTable2.Columns.Add("ItemID", typeof(int));
            DTTable2.Rows.Add(1);
            DTTable2.Rows.Add(5);
            DTTable2.Rows.Add(6); // table 2 contains { 1,5,6}

            var temp  = DTTable2.Copy();
            foreach (DataRow DR in temp.Rows)
            {
                int index = temp.Rows.IndexOf(DR);
                foreach (DataRow row in DTTable1.Rows) 
                if (DR["ItemID"].ToString() == row["ItemID"].ToString())
                {
                    DTTable2.Rows.RemoveAt(index);
                }
            }
            DTTable2.AcceptChanges();  // now table 2 contains  {6}
            
        
        }
    }
}


你好,如何y ou内容太短。内容太短。内容太小/太短了。


这篇关于如何使用C#比较和删除数据表行:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆