嗨,我在使用LINQ连接两个DataTable时遇到问题。表格具有像这样的列:
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();
问题是,结果仅显示table2中的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不够了解。帮助表示赞赏。谢谢!
如果表2中不存在该行,则将默认设置为0:
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 源码