【问题标题】:How to compare two DataTable with different number of columns?如何比较具有不同列数的两个 DataTable?
【发布时间】:2014-05-01 10:55:12
【问题描述】:

如果我想比较两个数据表并获得新数据表的差异,但我想保留一个未比较的列。 示例:

第一个数据表

姓名 |数字 ---- |------- 裘德 | 12 马克 | 14 斌 | 15

第二个数据表

姓名 ------ 裘德 罗宾 卡米尔

数据表必须有:

姓名 |数字
--------|----------
马克 | 14
斌 | 15

我有这种方法可以比较两个数据表并得到差异,但是我怎样才能得到数字。

public static DataTable CompareTables(DataTable first, DataTable second)
{
first.TableName = "FirstTable";
second.TableName = "SecondTable";

//Create Empty Table
DataTable table = new DataTable("Difference");

try
{
//Must use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

//Get Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[1];
firstcolumns[0] = ds.Tables[0].Columns[0];

DataColumn[] secondcolumns = new DataColumn[1];
secondcolumns[0] = ds.Tables[1].Columns[0];

//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

ds.Relations.Add(r);

//Create columns for return table
for (int i = 0; i < first.Columns.Count; i++)
{
table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
}

//If First Row not in Second, Add to return table.
table.BeginLoadData();

foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}

table.EndLoadData();

}
}
catch (Exception ex)
{

}

return table;
}

【问题讨论】:

  • 请提供有关 1) 的更多详细信息,您发现差异的依据是不同的列或数据之间的差异。 2)“我想保留一个未比较的列”是什么意思?那么,您想要两个表的并集还是交集以及基于什么标准?
  • 数据之间的差异,正如我在上面的示例中所示,Mark 和 Bin 是差异,因为它们在第二个表中不存在。
  • 因此,根据第一个表和第二个表之间的比较,您需要第一个表中的表三,其中名称存在于第一个表中但不存在于第二个表中。在您的情况下,您消除了两个表中都存在的 Jude,因此输出是 Mark 和 Bin 数字。如果我的理解是正确的,并且是基于数据的,那为什么在获取数据时不能处理呢?

标签: c# datatable


【解决方案1】:

让数据库处理这些事情:

SELECT name, number from table1 where name not in (select name from table2);

【讨论】:

    【解决方案2】:
        public static DataTable CompareTables(DataTable first, DataTable second)
        {
            second.PrimaryKey = new DataColumn[] {second.Columns["Name"]};
    
            DataTable difference = second.Clone();
    
            foreach (DataRow row in first.Rows) {
                if (second.Rows.Find(row["Name"]) == null)
                {
                    difference.ImportRow(row);
                }
            }
    
            return difference;
        }
    

    【讨论】:

      【解决方案3】:

      @user3527065 您的代码将抛出参数异常作为否。列数必须相同。 DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false); 我的情况下,第一列有 2 列,而第二列有 1 列,因此它会引发参数异常。

      【讨论】:

      • 但这如何回答这个问题?
      猜你喜欢
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多