C#在DataTables中查找非匹配值

时间:2015-05-22 20:31:16

标签: c# datatable matching relation

我正在努力解决以下问题:

有2个DataTables(在我的情况下是SSFE和FE)。 FE将包含与SSFE匹配的项目,但它也将包含SSFE中不存在的值。

例如

SSFE 1,2,3,4,5,6,9,10

FE 1,2,3,4,5,6,7,8,9,10,11

我需要的输出就是这个例子:7,8,11。

我正在使用以下代码查找匹配的项目:

        DataSet set = new DataSet();
        //wrap the tables in a DataSet.
        set.Tables.Add(SSFEData);
        set.Tables.Add(FEData);

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

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

        //Loop through table1 without using LINQ.
        for (int i = 0; i < SSFEData.Rows.Count; i++)
        {
            //If any rows in Table2 have the same Id as the current row in Table1
            if (SSFEData.Rows[i].GetChildRows(relation).Length > 0)
            {
                SSFEData.Rows[i]["PackageError"] = SSFEData.Rows[i].GetChildRows(relation)[0][1];
                SSFEData.Rows[i]["SaleError"] = SSFEData.Rows[i].GetChildRows(relation)[0][2];
            }
        }

应该有一个技巧来找到没有关系的这些项目。

任何建议都会很棒!

1 个答案:

答案 0 :(得分:0)

嗯,您当然可以使用AsEnumerable() 1 扩展方法将数据表转换为IEnumerables来使用一点LINQ。

我使用一些假设来说明这一点:

  1. &#34; ID&#34;是具有与FEDataSSFEData中的行相关的整数值的列。
  2. &#34; ID&#34;是FEDataSSFEData上的主键列。
  3. 然后,这将返回FEDataSSFEData中不存在的var notInSSFEData = FEData.AsEnumerable() .Where(x => SSFEData.Rows.Find((object)x.Field<int>("id")) == null) .ToList(); 行的列表:

    var notInSSFEData = FEData.AsEnumerable()
        .Where(x1 => !SSFEData.AsEnumerable().Any(x2 => x2.Field<int>("id") == x1.Field<int>("id")))
        .ToList();
    

    如果上面的假设2不成立(即&#34; id&#34;字段不是主键),则需要稍微复杂一点的查询。

    System.Data.DataSetExtensions

    1 这需要添加对\的引用(在System.Data.DataSetExtensions.dll中)。