Home > Backend Development > C++ > How to Perform an Inner Join of Two DataTables in C# using LINQ?

How to Perform an Inner Join of Two DataTables in C# using LINQ?

Barbara Streisand
Release: 2025-01-12 17:21:43
Original
835 people have browsed it

How to Perform an Inner Join of Two DataTables in C# using LINQ?

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:

  • T1(CustID, ColX, ColY)
  • T2(CustID, ColZ)

We need to create a joint table TJ containing the following fields:

  • TJ (CustID, ColX, ColY, ColZ)

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template