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

问题描述 投票:0回答:1

我有2个数据表:

  1. DataTable table1 --> 从Excel文件导入数据

样本数据:

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

样本数据:

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

我想连接这两个数据表,因此生成的数据表将是:

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

我尝试过以下查询:

var result = ( from a in table1.AsEnumerable(),
                     join b in table2.AsEnumerable()
                     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")
                 });

但是这个查询并没有给出 table1 中的所有列和 table2 中的“Dummy”列。它只返回 table1 中的“Account”和 table2 中的“Dummy”。

如何实现这一点以及如何将此查询结果存储到数据表中?

我希望数据表中有以下结果:

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
c# sql excel linq datatables
1个回答
2
投票

您需要将它们添加到您的

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")
 });
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.