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;

Technorati Tags:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s