Using C# LINQ for DataTable inner connection
Inner joins combine rows from two DataTables based on a common key. This is useful for tasks such as merging information from different tables or filtering data based on specific criteria.
Suppose we have two DataTables, T1 and T2, with the following fields:
We need to create a joint table TJ containing the following fields:
Using LINQ, we can perform an inner join on the CustID column:
<code class="language-csharp">var results = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"] select new { CustID = (int)table1["CustID"], ColX = (int)table1["ColX"], ColY = (int)table1["ColY"], ColZ = (int)table2["ColZ"] };</code>
This query generates a sequence of anonymous objects containing the concatenated columns. We can then iterate over the results and output them to the console:
<code class="language-csharp">foreach (var item in results) { Console.WriteLine(String.Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ)); }</code>
This code will produce the following output:
<code>ID = 1, ColX = 11, ColY = 21, ColZ = 31 ID = 2, ColX = 12, ColY = 22, ColZ = 32 ID = 3, ColX = 13, ColY = 23, ColZ = 33 ID = 4, ColX = 14, ColY = 24, ColZ = 34 ID = 5, ColX = 15, ColY = 25, ColZ = 35</code>
The above is the detailed content of How to Perform an Inner Join of Two DataTables in C# using LINQ?. For more information, please follow other related articles on the PHP Chinese website!