Inner join to DataTables using LINQ in C#
Inner join is a relational database operation that retrieves data from two or more tables based on a common column. In C#, you can perform inner joins on DataTables using a variety of technologies, including LINQ.
LINQ method:
If LINQ is an option, the following code snippet demonstrates how to perform an inner join on two DataTables (T1 and T2):
<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)); // 添加一些示例数据 for (int i = 1; i <= 5; i++) { dt1.Rows.Add(i, 10 + i, 20 + i); dt2.Rows.Add(i, 30 + i); } // 使用LINQ执行内连接 var results = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on table1.Field<int>("CustID") equals table2.Field<int>("CustID") select new { CustID = table1.Field<int>("CustID"), ColX = table1.Field<int>("ColX"), ColY = table1.Field<int>("ColY"), ColZ = table2.Field<int>("ColZ") }; // 输出结果 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 LINQ query performs an inner join using the on
clause, which specifies that the CustID
columns of the two tables should be equal. The result is returned as an anonymous type containing the CustID
, ColX
, ColY
, and ColZ
columns.
Output:
This code will output the following results:
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
The above is the detailed content of How to Perform an Inner Join on DataTables in C# using LINQ?. For more information, please follow other related articles on the PHP Chinese website!