LINQ连接两个数据表
您好,我有一个问题,join两个使用LINQ的数据表。 表格有这样的列:
table1 table2 ID, name ID, stock 1, item1 1, 100 2, item2 3, 50 3, item3
我用linqjoin这样的:
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没有足够的了解。 帮助赞赏。 谢谢!
这将让你默认为0,如果该行不存在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 源码
尝试这个:
var result = from dataRows1 in table1.AsEnumerable() join dataRows2 in table2.AsEnumerable() on dataRows1.ID equals dataRows2.ID into ps from r in ps.DefaultIfEmpty() select new { C= dataRows1 , r == null ? 0 : dataRows2.Stock};
你只需要使用像这样的join..into子句
var result = from dataRows1 in table1.AsEnumerable() join dataRows2 in table2.AsEnumerable() on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID") into rows from row in rows.DefaultIfEmpty() select dtResult.LoadDataRow(new object[] { dataRows1.Field<string>("ID"), dataRows1.Field<string>("name"), row==null? null : row.Field<int>("stock"), }, false);
尝试这个
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 : dataRows2.Field<int>("stock") }, false);