Thursday, 8 July 2010

Order Matters – LINQ

One of my colleague ran into this problem when using LINQ to join two tables. The problem is that he has two tables a & b where he is joining tables on column called key on both the tables. Following is what he had in the beginning

var list = from firstTable in a

              join secondTable in b

              on firstTable.Key == secondTable.Key

              select a;

This is a very straight forward query. On first glace there is nothing wrong with that. But when he tries to enter the above mentioned code, VS 2010 did not let him complete and was give error “The name ‘secondTable’ is not in scope on the left side of ‘equals’”  Couple of things you have to remember when you are using Linq to do joins

  • The order of comparison matters. So always use first table first and compare it against second table.
  • All LINQ joins are equijoins. so instead of using == you should use equals

So the correct LINQ query should be like the following

var list = from firstTable in a

              join secondTable in b

              on firstTable.Key equals secondTable.Key

              select a;

0 comments:

Post a Comment