比如dt1数据是
id price
1 100
2 100
dt2
id excelprice
1 100
3 200
想要得出来的数据是:
id price excleprice
1 100 100
2 100 null
3 null 100
如何实现?
首先想到的实现方式是:
- void Main()
- {
- DataTable dtA = new DataTable();
- dtA.Columns.Add("id", typeof(int));
- dtA.Columns.Add("price", typeof(string));
- dtA.Rows.Add(1, "100");
- dtA.Rows.Add(2, "100");
- DataTable dtB = dtA.Clone();
- dtB.Rows.Add(1, "100");
- dtB.Rows.Add(3, "100");
- DataTable dtC = dtA.Clone();
- dtC.Columns.Add("price_excel");
- var fullJoinData =(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 ? "Null" : b.Field<string>("price")
- }).Union
- (
- from b in dtB.AsEnumerable()
- join a in dtA.AsEnumerable()
- on b.Field<int>("id") equals a.Field<int>("id") into g
- from a in g.DefaultIfEmpty()
- select new
- {
- id = b.Field<int>("id"),
- price = a == null ? "Null" : a.Field<string>("price"),
- price_excel =b.Field<string>("price")
- }
- );
- fullJoinData.ToList().ForEach(q => dtC.Rows.Add(q.id, q.price, q.price_excel));
- }
后来写了一个条理比较清晰的实现方式:
- void Main()
- {
- DataTable dtA = new DataTable();
- dtA.Columns.Add("id", typeof(int));
- dtA.Columns.Add("price", typeof(string));
- dtA.Rows.Add(1, "100");
- dtA.Rows.Add(2, "100");
- DataTable dtB = dtA.Clone();
- dtB.Rows.Add(1, "100");
- dtB.Rows.Add(3, "100");
- DataTable dtC = dtA.Clone();
- dtC.Columns.Add("price_excel");
- var leftData=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 ? "Null" : b.Field<string>("price")
- };
- var rightData=from b in dtB.AsEnumerable()
- where !dtA.AsEnumerable().Select(a=>a.Field<int>("id")).Contains(b.Field<int>("id"))
- select new
- {
- id = b.Field<int>("id"),
- price = "Null",
- price_excel =b.Field<string>("price")
- };
- var fullJoinData =leftData.Union(rightData);
- fullJoinData.ToList().ForEach(q => dtC.Rows.Add(q.id, q.price, q.price_excel));
- }