All posts by noam

Joining DataTables in LINQ

[Image via Patou Fine Art]

The Problem

Recently, I encountered a situation where I had to join two Data Tables from databases on two different servers. Had they been on the same server, I would do this in SQL with a simple JOIN statement, but since the databases were on different servers, my options were limited. I could:

  1. Use a linked server (http://msdn.microsoft.com/en-us/library/ms188279.aspx)
    But: This wasn’t really an option because I wouldn’t be able to modify production servers
  2. Use System.Data and create a DataRelation
    But: DataRelations are clunky and don’t perform LEFT OUTER JOIN’s very well
  3. Create a new DataTable and copy rows over manually (with, for example, a foreach loop)
    But: This would be painfully slow
    And: I’d have to duplicate a lot of null-row handling logic that LINQ and SQL do themselves
  4. Join the tables in the codebehind using C#’s own SQL-like syntax, LINQ.
    But: I had no idea how to use LINQ.

The Solution

After some research, I decided on option #4. To get a basic overview of LINQ, I started by going through 101 LINQ Samples and trying to learn the LINQ syntax. This was my first attempt at getting a method to join two DataTables: Continue reading Joining DataTables in LINQ