简体   繁体   English

如何比较不同数据表中的2列

[英]How to compare 2 columns in different datatables

table1 表格1

id  | fileName   |  fileDateTime
1   | somefile   |  somedatetime
2   | somefile2  |  somedatetime2

table2 表2

id   |   fileName    |   fileDateTime
     |   somefile1   |   somedatetime1
     |   somefile2   |   somedatetime2

output table3 输出表3

id   |   fileName    |    fileDatetime
     |   somefile1   |    somedatetime1

I want to compare the 2 tables (column 2 & 3 only) and only have what is not in both tables, there is no ID field in the 2nd table. 我想比较2个表(仅第2列和第3列),只有两个表中都没有的东西,第二个表中没有ID字段。 Then I plan on parsing the data in the file and add file info to database to record file has been parsed. 然后我计划解析文件中的数据,并将文件信息添加到数据库中以记录已解析的文件。 I am having trouble comparing the 2 fields. 我在比较2个字段时遇到问题。 This does not seem to work. 这似乎不起作用。

for (int i = 0; i < finalTable.Rows.Count; i++)
{
    for (int r = 0; r < filesTable.Rows.Count; i++)
    {
        if (finalTable.Rows[i][2] == filesTable.Rows[r][2])
        {
            finalTable.Rows.Remove(finalTable.Rows[i]);
        }
    }
}

Assuming the value is a string, you could just do 假设值是一个字符串,您可以做

for (int i = 0; i < finalTable.Rows.Count; i++)
{
    for (int r = 0; r < filesTable.Rows.Count; i++)
    {
        if (finalTable.Rows[r].Field<string>(2) == filesTable.Rows[r].Field<string>(2))
        {
            finalTable.Rows.Remove(finalTable.Rows[i]);
        }
    }
}

If it's another type, just change the <string> for the real type ! 如果是其他类型,只需将<string>更改为实类型!

You can use Linq to achieve it as shown below. 您可以使用Linq来实现它,如下所示。

Assuming your fields are string. 假设您的字段是字符串。 For other datatype you can cast them accordingly: 对于其他数据类型,您可以相应地强制转换它们:

using System.Data.Linq;
......
......
// Merge both tables data and group them by comparing columns values
dt1.Merge(dt2); 
var g = dt1.AsEnumerable()
        .GroupBy(x => x[0]?.ToString() + x[1]?.ToString()) // You can build Unique key here, I used string concatination
        .ToDictionary(x => x.Key, y => y.ToList());

var unique = dt1.Clone();

foreach (var e in g)
{
    if (e.Value.Count() == 1) // In either table - Intersaction 
    {
        e.Value.CopyToDataTable(unique, LoadOption.OverwriteChanges);
    }

    if (e.Value.Count() == 2) 
    {
        // In both tables -Union
    }
}

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

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