LINQ retrieves values ​​from a table where fields (of a specific column) are not equal to another table

I have two tables with a common column, how can I get the first table where the values ​​of that column are not equal to the values ​​of the column of another table?

Here's an example:

  table1ID | foo    | fooBool        table2ID | foo      | fooin
 ----------------------------        -----------------------------

     1    |  test1  | true              1     |   test2  |    5
     2    |  test2  | true              2     |   test3  |    7
     3    |  test3  | true
     4    |  test4  | false

      

Therefore, the result of a LINQ query for the first table that has foo values ​​not equal to those of table2:

table1ID | foo    | fooBool
---------------------------    
   1     | test1  | true
   4     | test4  | false

      

+1


source to share


2 answers


var results = from t1 in db.table1
              from t2 in db.table2
              where t1.foo != t2.foo
              select t1

      



+3


source


You can also use Intersect()

IEnumerable Extension

var results = db.table1.Intersect(db.table2);

      

Or in LINQ

var codes = from intersected in db.table1.Intersect(db.table2)
            select intersected.foo;

      

This will create

 results 
 ----------
 test2
 test3

      

Update



Thanks to Joe for pointing out that he Intersect

will create common elements (added example above). What you would like is Except

an extension method.

var results = db.table1.Except(db.table2);

      

Or in LINQ

var codes = from diff in db.table1.Except(db.table2)
            select diff.foo;

      

This will create

 results 
 ----------
 test1
 test4

      

+2


source







All Articles