10101
10101

Reputation: 2412

Compare same DataTable by certain columns, return mismatches to CopyToDataTable()

I have two DataTables (Columns: ID, MODEL, POWER, CLASS):

Table 1:

411 Audi   500 300
412 BMW    400 800
413 Lexus  200 700

Table 2:

876 Audi   500 300
896 BMW    400 870
832 Lexus  200 700
874 Fiat   250 450

As result I need to get (mismatch by at least one criteria, not taking in consideration ID):

412 BMW    400 800
896 BMW    400 870

I can't perform Except because there is first number that does not match between two (4.. & 8..). If I am querying before merging two DataTables together:

var matched = from table1 in MainProcess.dt1.AsEnumerable()
     join table2 in MainProcess.dt2.AsEnumerable()
     on table1.Field<string>("MODEL") equals table2.Field<string>("MODEL")

     where table1.Field<string>("POWER") != table2.Field<string>("POWER")
     || table1.Field<string>("CLASS") != table2.Field<string>("CLASS")
                 select table1;

     return matched.CopyToDataTable();

As result I am getting only one of results 412 BMW 400 800. I have tried with .Count() > 1 && .Count() < 1 but it didn't work either.

What is the right way to solve this problem? I guess I need to merge two DataTables before querying?

Upvotes: 0

Views: 30

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27396

You were so close:

var matched = from table1 in MainProcess.dt1.AsEnumerable()
    join table2 in MainProcess.dt2.AsEnumerable()
       on table1.Field<string>("MODEL") equals table2.Field<string>("MODEL")
    where table1.Field<string>("POWER") != table2.Field<string>("POWER")
        || table1.Field<string>("CLASS") != table2.Field<string>("CLASS")
    select new { table1, table2 };

var result = matched.SelectMany(x => new[] { x.table1, x.table2 })
    .CopyToDataTable();

Upvotes: 1

Related Questions