如何将一个数据表中的某些列添加到另一个数据表中

本文关键字:数据表 添加 另一个 一个 | 更新日期: 2023-09-27 18:01:44

我的数据表dt1有productID、productName和productPrice列,dt2有orderID、productID、productName、productPrice和totalPrice列。我如何得到dt1信息到dt2,而只是进入productID?

如何将一个数据表中的某些列添加到另一个数据表中

我不确定我是否正确理解了你,我如何阅读它,你想要c#数据表中的JOIN函数。我很久以前就这么做了,所以我认为有更好的方法…

    /// <summary>
    /// Give a Table that contains the foreignkeys it returns a Table with a Description instead of the Key
    /// The ID in the source has to be Column[0]
    /// </summary>
    /// <param name="foreignkeys">Foreignkey in you Table</param>
    /// <param name="source">The Table the foreignkey refers to</param>
    /// <param name="_foreigncolumn">Header of Foreignkeycolumn</param>
    /// <param name="_sourcecolumn">Header description column in source Table</param>
    /// <returns></returns>
    public DataTable getDatabyForeignKey(DataTable foreignkeys, DataTable source, string _foreigncolumn, string _sourcecolumn)
    {
        try
        {
            DataTable displayname = new DataTable();
            displayname.Columns.Add("ID");
            //Maybe change that to a parameter as well (amount + header)
            displayname.Columns.Add("Description");
            for (int i = 0; i < foreignkeys.Rows.Count; i++)
            {
                for (int j = 0; j < source.Rows.Count; j++)
                {
                    string s = source.Rows[j][0].ToString();
                    string ss = foreignkeys.Rows[i][_foreigncolumn].ToString();
                    if (source.Rows[j][0].ToString() == foreignkeys.Rows[i][_foreigncolumn].ToString())
                    {
                        foreignkeys.Rows[i][_foreigncolumn] = source.Rows[j][_sourcecolumn];
                    }
                }
            }
        }
        catch (Exception)
        {
            MessageBox.Show(ex.Message);               
        }
        return foreignkeys;
    }