将2行数据行连接到C#行中 [英] join 2 datarow rows into one row C#

查看:188
本文介绍了将2行数据行连接到C#行中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我知道我可以通过sql进行2行联接,但我的程序未使用它 我有2个数据表,我取每一行,与另一张表的行进行比较,并希望从中进行联接

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 a join out of it

 public DataTable joinTables (DataTable t1, DataTable t2)
    {
        DataTable joinTable = new DataTable();
        foreach (DataRow r1 in t1.Rows)
        {
            foreach (DataRow r2 in t2.Rows)
            {
                ///if (....)
                    joinTable.ImportRow(joinRows(r1,r2));
            }
        }
        return joinTable;
    }
    public DataRow joinRows (DataRow r1, DataRow r2)
    {
        DataRow joinRow = new DataRow();
        ///....
        return joinRow;
    }

推荐答案

我认为您可能大大低估了所寻找内容的复杂性,但是下面的代码可以做到这一点,但是它有一些主要假设我来讨论.

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];
}

假设

  1. 每个DataTable具有相同的行数.
  2. 这些DataTable对象中的行按希望它们按索引合并的顺序排序.
  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.

这篇关于将2行数据行连接到C#行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆