tags:

views:

61

answers:

2

I have two tables which have a column in common , how can I retreive the first table where the values of it's column are not equal to the values of the column of the other table?

Here is 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 the LINQ query for the first table that has values of foo not equal that of table2 are:

table1ID | foo    | fooBool
---------------------------    
   1     | test1  | true
   4     | test4  | false
+3  A: 
var results = from t1 in db.table1
              from t2 in db.table2
              where t1.foo != t2.foo
              select t1
Darren Kopp
+2  A: 

You could also use the 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 would produce

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

Update

Thanks to Joe for pointing out that Intersect would produce the common items (added sample above). What you would want is the Except 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 would produce

 results 
 ----------
 test1
 test4
bendewey
The intersect operator produces the set intersect of two sequences. This is the opposite of what the OP is trying to achieve. The Except operator would be the appropriate one here.
Winston Smith
thanks Joe, I updated accordingly
bendewey
But that only works for the same kind of table no?
Drahcir
AFAIK, yes, although you may be able to write something using the IEqualityComparer. You could also write your own Generic Extension method that accepts a Predicate<T> for comparison.
bendewey