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

标签 c# performance algorithm datatable compare

我正在处理 2 个数据表:

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

我需要在这些表之间匹配的值是整数,两个表都是从小到大排序的。 我的想法是从 FFE 中的第一项开始搜索,开始遍历 SSFE,当我找到匹配项时 -> 记住当前索引 -> 保存匹配项 -> 从 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 类。它在数据集中的两个数据表之间创建外键/连接。

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 场比赛。

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

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

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

关于C# 比较 2 个数据表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635374/

相关文章:

C# 客户端应用程序与 Web 应用程序

c# - 如何将属性从一个 .net 对象复制到另一个

performance - 为什么该程序的 F# 版本比 Haskell 版本快 6 倍?

python - 为什么在 Python 中计算点距离这么慢?

java - Java 中按外观对字符串排序

algorithm - Fence - 来自波兰信息学奥林匹克竞赛的任务

c# - 通过 WCF 公开自定义类中的成员函数

C# 如何使图形对象可克隆

C# 预先捕获异常或验证参数

c - realloc() 的性能影响