Use LINQ to efficiently connect DataTable
Suppose there are two DataTables, T1 and T2 respectively, with the following fields:
<code>T1(CustID, ColX, ColY) T2(CustID, ColZ)</code>
In order to efficiently get a combined DataTable "TJ" containing "CustID", "ColX", "ColY" and "ColZ" fields in C#, you can use the following LINQ solution:
<code class="language-csharp">DataTable dt1 = new DataTable(); dt1.Columns.Add("CustID", typeof(int)); dt1.Columns.Add("ColX", typeof(int)); dt1.Columns.Add("ColY", typeof(int)); DataTable dt2 = new DataTable(); dt2.Columns.Add("CustID", typeof(int)); dt2.Columns.Add("ColZ", typeof(int)); // ... (此处应添加填充dt1和dt2数据的代码) ... var query = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on table1["CustID"] equals table2["CustID"] select new { CustID = table1["CustID"], ColX = table1["ColX"], ColY = table1["ColY"], ColZ = table2["ColZ"] }; DataTable TJ = new DataTable(); TJ.Columns.Add("CustID", typeof(int)); TJ.Columns.Add("ColX", typeof(int)); TJ.Columns.Add("ColY", typeof(int)); TJ.Columns.Add("ColZ", typeof(int)); foreach (var item in query) { TJ.Rows.Add(item.CustID, item.ColX, item.ColY, item.ColZ); } // ... (此处应添加显示TJ DataTable内容的代码) ...</code>
This code demonstrates how to use LINQ to make an inner join between two DataTables. It creates two DataTables, fills them with sample data (the data filling part is omitted here), and then uses a LINQ query to perform the join operation. The results of the connection will be displayed in the console (the results display part is also omitted here). Please note that additional data filling and result display code is required to fully function.
The above is the detailed content of How to Efficiently Join Two DataTables in C# Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!