简体   繁体   中英

C# Find non matching values in DataTables

I'm struggling with the following problem:

There are 2 DataTables (SSFE and FE in my case). FE will contain items that match with SSFE, but it will also contain values not present in SSFE.

For Example

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

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

The ouput I need is in this example : 7, 8, 11.

I'm using the following code to find items that do match:

        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];
            }
        }

There should be an trick to find these items that do not have an relation.

Any suggestion will be great!

Well, you could of course use a little bit of LINQ by turning the data tables into IEnumerables using the AsEnumerable() 1 extension method.

I am using a few assumptions to illustrate this:

  1. "id" is the column with an integer value relating rows in FEData and SSFEData .
  2. "id" is the primary key column on both FEData and SSFEData .

Then this will return a list of rows from FEData that are not present in SSFEData :

var notInSSFEData = FEData.AsEnumerable()
    .Where(x => SSFEData.Rows.Find((object)x.Field<int>("id")) == null)
    .ToList();

If assumption 2 above does not hold (ie the "id" field is not the primary key), a slightly more elaborate query is required.

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

1 this requires adding a reference to System.Data.DataSetExtensions (in System.Data.DataSetExtensions.dll).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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