简体   繁体   English

C# 使用 LINQ 连接两个数据表

[英]C# join two datatables using LINQ

I have 2 datatables:我有 2 个数据表:

  1. DataTable table1 --> importing data from Excel file DataTable table1 --> 从 Excel 文件导入数据

Sample data:样本数据:

Account, Name, Address, Phone 
A05911,  Test1, LA,    1234
A05912,  Test2, NY,    1235
A05912,  Test2, NY,    1235
A05913,  Test3, BO,    1239
  1. DataTable table2 -- importing data from SQL database DataTable table2 -- 从 SQL 数据库导入数据

Sample data:样本数据:

 Account, Dummy
 A05911,  yyyy1
 A05912,  xxxx2
 A05913,  zzzz3

I want to join these 2 datatables so the resulting datatable will be:我想加入这两个数据表,所以生成的数据表将是:

Account, Dummy, Name, Address, Phone 
A05911,  yyyy1, Test1, LA,    1234
A05912,  xxxx2, Test2, NY,    1235
A05912,  xxxx3, Test2, NY,    1235
A05913,  zzzz4, Test3, BO,    1239

I have tried with following query:我尝试过以下查询:

var result = ( from a in table1.AsEnumerable(),
                     join b in table2.AsEnumberable()
                     on a.Field<string>("Account") equals b.Field<string>("Account") 
                 into temp from res in temp.DefaultIfEmpty()
                 select new 
                 {
                      Account = a.Field<string>("Account"),
                      Test = res == null ? null : res.Field<string>("Dummy")
                 });

But this query does not give all the columns from table1 and 'Dummy' column from table2.但是这个查询并没有给出 table1 中的所有列和 table2 中的“虚拟”列。 It only returns 'Account' from table1 and its 'Dummy' from table2.它只从 table1 返回“Account”,从 table2 返回“Dummy”。

How do I achieve this and also how do I store this query result into a datatable?我如何实现这一点,以及如何将此查询结果存储到数据表中?

I want the following result in datatable:我想要数据表中的以下结果:

Account, Dummy, Name, Address, Phone 
A05911,  yyyy1, Test1, LA,    1234
A05912,  xxxx2, Test2, NY,    1235
A05912,  xxxx3, Test2, NY,    1235
A05913,  zzzz4, Test3, BO,    1239

You need to add them to your select :您需要将它们添加到您的select

 select new 
 {
      Account = a.Field<string>("Account"),
      Name = a.Field<string>("Name"),
      Address = a.Field<string>("Address"),
      Phone = a.Field<string>("Phone"),
      Test = res == null ? null : res.Field<string>("Dummy")
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM