join 2 datarow rows into one row C#

后端 未结 3 1661
不知归路
不知归路 2021-01-17 02:32

while i know i can make a join of 2 rows via sql, my program doesn\'t use it i have 2 datatables and i take each row, compare to the rows on the other table and want to make

3条回答
  •  情书的邮戳
    2021-01-17 02:59

    I think you may have vastly underestimated the complexity of what you're looking for, but here is some code that will do it, but it has some major assumptions I'll discuss.

    public DataTable joinTables (DataTable t1, DataTable t2)
    {
        DataTable t = new DataTable();
        AddColumns(t1, t);
        AddColumns(t2, t);
    
        for (int i = 0; i < t1.Rows; i++)
        {
            DataRow newRow = t.NewRow();
    
            for (int j = 0; j < t1.Columns.Count; j++)
            {
                SetMergedRowValue(t1.Rows[i], newRow, j);
                SetMergedRowValue(t2.Rows[i], newRow, j);
            }
    
            t.Rows.Add(newRow);
        }
    
        t.AcceptChanges();
    }
    
    private void AddColumns(DataTable source, DataTable target)
    {
        foreach (DataColumn c in source.Columns)
        {
            target.Columns.Add(string.Format("{0}_{1}", source.TableName, c.ColumnName), c.DataType);
        }
    }
    
    private void SetMergedRowValue(DataRow source, DataRow target, int index)
    {
        var columnName = string.Format("{0}_{1}", source.Table.TableName, source.Table.Columns[index]);
        target[columnName] = source[index];
    }
    

    Assumptions

    1. Each DataTable has the same number of rows.
    2. The rows in those DataTable objects are sorted in the order you want them merged by index.

    These assumptions are major. In short, though this produces the desired outcome, I'm unsure it's really what you're looking for, and I'm unsure you're really sure what you're looking for.

提交回复
热议问题