C# 比较 2 个数据表中的值

C# Comparing values in 2 DataTables

我正在处理 2 个数据表:

  1. SSFE:包含我要查找的值
  2. FFE:大于、小于或等于 SSFE,但不一定包含 SSFE 的每个值

我需要在这些表之间匹配的值是整数,两个表都是从小到大排序的。 我的想法是开始搜索 FFE 中的第一项,开始遍历 SSFE,当我找到匹配项时 -> 记住当前索引 -> 保存匹配项 -> select FFE 中的下一项并从上一个索引继续.

FFE 也可以包含整数,但也可以包含字符串,这就是我将值转换为字符串并进行比较的原因。

我编写了一些代码,但是它花费了太多时间。 比较 SSFE(1.000 件)和 FFE(127.000 件)大约需要一分钟。

int whereami = 0;
bool firstiteration = true;
for (int i = 0; i < FFEData.Rows.Count - 1; i++)
{
    for (int j = 0; j < SSFEData.Rows.Count - 1; j++)
    {
        if (firstiteration)
        {
            j = whereami;
            firstiteration = false;
        }
        if (SSFEData.Rows[j][0] == FFEData.Rows[i][0].ToString())
        {
            found++;
            whereami = j;
            firstiteration = true;
            break;
        }
    }
}

我只存储了我发现的测试次数。在此示例中,它将找到 490 个匹配项,但这并不相关。

有什么建议就太好了!

可以试试 DataRelation class。它在数据集中的两个数据表之间创建外键/连接。

using System.Data;
using System.Text;

public int GetMatches(DataTable table1, DataTable table2)
{
    DataSet set = new DataSet();

    //wrap the tables in a DataSet.
    set.Tables.Add(table1);
    set.Tables.Add(table2);

    //Creates a ForeignKey like Join between two tables.
    //Table1 will be the parent. Table2 will be the child.
    DataRelation relation = new DataRelation("IdJoin", table1.Columns[0], table2.Columns[0], false);

    //Have the DataSet perform the join.
    set.Relations.Add(relation);

    int found = 0;

    //Loop through table1 without using LINQ.
    for(int i = 0; i < table1.Rows.Count; i++)
    {
        //If any rows in Table2 have the same Id as the current row in Table1
        if (table1.Rows[i].GetChildRows(relation).Length > 0)
        {
            //Add a counter
            found++;

            //For debugging, proof of match:
            //Get the id's that matched.
            string id1 = table1.Rows[i][0].ToString();

            string id2 = table1.Rows[i].GetChildRows(relation)[0][0].ToString();

        }
    }

    return found;
}

我用 nvarchar(2) 字符串随机填充了两个非索引表,每个表有 10,000 行。比赛用时不到 1 秒,包括填充表格所花费的时间。我平均会得到 3500 到 4000 个匹配 运行。

但是,主要的警告是要匹配的 DataColumns 必须 是相同的数据类型。因此,如果两列都是字符串,或者至少是存储为字符串的整数,那么这将起作用。

但是如果一列是整数,您将不得不添加一个新列,并首先将整数作为字符串存储在该列中。字符串翻译会增加大量时间。

另一个选项是将表上传到数据库并执行查询。如此大的上传可能需要几秒钟,但查询也将不到一秒钟。所以还是比60秒+好。