使用linq机制 实现datatable连表查询 结果赋值到一个新的datatable

 
 

using System.Data;
using System.Linq;

//注意项目要引用System.Data.DataSetExtensions


DataTable dtA = new DataTable();
dtA.Columns.Add("id", typeof(int));
dtA.Columns.Add("price", typeof(string));
dtA.Rows.Add(1, "111");
dtA.Rows.Add(2, "222");
dtA.Rows.Add(3, "333");
dtA.Rows.Add(4, "444");
dtA.Rows.Add(5, "555");

DataTable dtB = dtA.Clone();
dtB.Rows.Add(1, "121");
dtB.Rows.Add(2, "221");
dtB.Rows.Add(3, "331");

DataTable dtC = dtA.Clone();
dtC.Columns.Add("price_excel");

var query = from a in dtA.AsEnumerable()
join b in dtB.AsEnumerable()
on a.Field<int>("id") equals b.Field<int>("id") into g
from b in g.DefaultIfEmpty()
select new
{
id = a.Field<int>("id"),
price = a.Field<string>("price"),
price_excel = b == null ? "None" : b.Field<string>("price")
};

query.ToList().ForEach(q => dtC.Rows.Add(q.id, q.price, q.price_excel));

使用linq机制 实现datatable连表查询 结果赋值到一个新的datatable - lijiexiongxiong - 风语博客

猜你喜欢

转载自blog.csdn.net/shan1774965666/article/details/78051498