将列从一个数据集添加到另一个数据集

本文关键字:数据集 一个 添加 另一个 | 更新日期: 2023-09-27 18:32:10

有一个数据集Ds1和数据集Ds2,DS1有Product_ID,产品信息,ds2有Product_ID,product_type。

对于匹配product_id,我想将Product_tye列从 ds2 添加到 ds1 .

注意:Product_id不是 ds 1 中的主键,但结果集具有许多具有相同product_id的乘积。在 ds 2 中,product_id是唯一的。此外,这些数据来自不同服务器上的两个不同数据库,并且具有不同的凭据,因此不能使用SQL联接。

我尝试使用 linq 来实现这一点,但没有得到所需的输出,如果我弄错了什么,请纠正我.

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
//After both the datatble has values, using linq to add datatble columsn, 
DataTable result = (from t1 in dt1.AsEnumerable()
                            join t2 in dt2.AsEnumerable() on t1.Field<string>("productID") equals t2.Field<string>("productID")
                            select t1).CopyToDataTable();

将列从一个数据集添加到另一个数据集

选择两个表

DataTable result = (from t1 in dt1.AsEnumerable()
                        join t2 in dt2.AsEnumerable() on t1.Field<string>("productID")  
                                     equals t2.Field<string>("productID")
                        select new {t1,t2}
                    ).CopyToDataTable();

或选择所选列

DataTable result = (from t1 in dt1.AsEnumerable()
                        join t2 in dt2.AsEnumerable() on t1.Field<string>("productID") 
                                      equals t2.Field<string>("productID")
                        select new {
                         productId = t1.productID, 
                         col2 = t1.col2,...,
                         productType = t2.pruductType
                    ).CopyToDataTable();

注意:我认为产品ID类型应该是int类型,因此在这种情况下string替换为int

我刚刚为您创建了一个简单示例,您所要做的就是使用您自己的代码更改我的代码中的列名:

        DataTable table1 = new DataTable();
        DataTable table2 = new DataTable();
        table1.Columns.Add("id", typeof(int));
        table1.Columns.Add("name", typeof(string));
        table2.Columns.Add("id", typeof(int));
        table2.Columns.Add("age", typeof(int));
        table1.Rows.Add(1, "mitja");
        table1.Rows.Add(2, "sandra");
        table1.Rows.Add(3, "nataška");
        table2.Rows.Add(1, 31);
        table2.Rows.Add(3, 24);
        table2.Rows.Add(4, 46);
        DataTable targetTable = table1.Clone();
        //create new column
        targetTable.Columns.Add("age");
        var results = from t1 in table1.AsEnumerable()
                      join t2 in table2.AsEnumerable() on t1.Field<int>("id") equals t2.Field<int>("id")
                      select new
                      {
                          ID = (int)t1["id"],
                          NAME = (string)t1["name"],
                          AGE = (int)t2["age"]
                      };
        foreach (var item in results)
            targetTable.Rows.Add(item.ID, item.NAME, item.AGE);

在任何情况下,定义变量类型(int、string等)时都要小心!!希望对您有所帮助。