[英]C# join two datatables using LINQ
我有 2 个数据表:
样本数据:
Account, Name, Address, Phone
A05911, Test1, LA, 1234
A05912, Test2, NY, 1235
A05912, Test2, NY, 1235
A05913, Test3, BO, 1239
样本数据:
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.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")
});
但是这个查询并没有给出 table1 中的所有列和 table2 中的“虚拟”列。 它只从 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
您需要将它们添加到您的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.