LINQ 连接两个数据表 [英] LINQ join two DataTables
本文介绍了LINQ 连接两个数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用 LINQ 连接两个数据表时遇到问题.表格有这样的列:
Hi I have a problem joining two DataTables using LINQ. Tables have columns like this:
table1 table2
ID, name ID, stock
1, item1 1, 100
2, item2 3, 50
3, item3
我用 linq 加入这样的:
I used linq to join like this:
DataTable dtResult = new DataTable();
dtResult.Columns.Add("ID", typeof(string));
dtResult.Columns.Add("name", typeof(string));
dtResult.Columns.Add("stock", typeof(int));
var result = from dataRows1 in table1.AsEnumerable()
join dataRows2 in table2.AsEnumerable()
on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID")
select dtResult.LoadDataRow(new object[]
{
dataRows1.Field<string>("ID"),
dataRows1.Field<string>("name"),
dataRows2.Field<int>("stock"),
}, false);
result.CopyToDataTable();
问题是,结果只显示了表 2 中的 ID.
Problem is, result only shows IDs which are in the table2.
dtResult
ID, name, stock
1, item1, 100
3, item3, 50
我还需要显示丢失的项目.这是想要的结果:
I need to show also the missing items. This is the wanted result:
dtResult
ID, name, stock
1, item1, 100
2, item2, 0 //Prefer if it is "0", otherwise can be left "null"
3, item3, 50
我相信我应该做左外连接,但我对 linq 没有足够的了解.帮助表示赞赏.谢谢!
I believe I should do left outer join, but I do not have enough knowledge about linq. Help appreciated. Thank you!
推荐答案
如果表 2 中不存在该行,这将让您默认为 0:
This will let you default to 0 if the row doesn't exist in table2:
var result = from dataRows1 in table1.AsEnumerable()
join dataRows2 in table2.AsEnumerable()
on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID") into lj
from r in lj.DefaultIfEmpty()
select dtResult.LoadDataRow(new object[]
{
dataRows1.Field<string>("ID"),
dataRows1.Field<string>("name"),
r == null ? 0 : r.Field<int>("stock")
}, false);
MSDN 来源
这篇关于LINQ 连接两个数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文