如何在两个数据列表上使用LINQ加入在一个数据台上没有匹配记录时用0或null填充空字段
我使用LINQ连接两个DataTables有问题。
表具有类似的列:
table1 table2
ID, name ID, stock
1, item1 1, 100
2, item2 3, 50
3, item3
我使用Linq这样的加入:
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:
dtResult
ID, name, stock
1, item1, 100
3, item3, 50
我也需要显示缺失的项目。这是理想的结果:
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 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
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();
The problem is that the result only shows IDs which are in the table2:
dtResult
ID, name, stock
1, item1, 100
3, item3, 50
I need to show the missing items, too. This is the desired result:
dtResult
ID, name, stock
1, item1, 100
2, item2, 0 //Prefer if it is "0", otherwise can be left "null"
3, item3, 50
I believe I should do left outer join, but I do not have enough knowledge about LINQ.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果table2:
msdn source
This will let you default to 0 if the row doesn't exist in table2:
MSDN source
尝试以下操作:
try this:
您只需要使用 join..into strapo strapo strapor
you simply need use join..into clause like this
尝试一下
try this