日期:2014-05-18  浏览次数:20558 次

Linq_join的问题
现在有2个DataTable.
A是数据库中的数据,(模拟)
C# code

  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");


B是Excel中的数据(模拟)
C# code

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


现在可以查出,A中(DB)存在但是B中(Excel)不存在的数据。
C# code

 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));
        gwinfo.DataSource = dtC;
        gwinfo.DataBind();



如何可以同时查出B中(Excel)存在A中(DB)中不存在的数据呢,?

------解决方案--------------------
C# code

//或许这样写,条理更清晰一点:
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 query =leftData.Union(rightData);
 query.ToList().ForEach(q => dtC.Rows.Add(q.id, q.price, q.price_excel));

}