简体   繁体   中英

join 2 datarow rows into one row C#

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

Here's an example of two ways to do join using LINQ.

        var t1 = new DataTable();
        var t2 = new DataTable();
        t1.Columns.Add("id", typeof (Int32));
        t1.Columns.Add("data", typeof (String));
        t2.Columns.Add("id", typeof (Int32));
        t2.Columns.Add("data", typeof (Int32));

        t1.Rows.Add(new {id=1, data="John"});
        t1.Rows.Add(new {id = 2, data = "Mary"});

        t2.Rows.Add(new {id = 1, data = "100"});
        t2.Rows.Add(new {id = 2, data = "200"});


        var results = from x in t1.Select()
                      join y in t2.Select() on (Int32) x["id"] equals (Int32) y["id"]
                      select (new {id = x["id"], name = x["data"], number = y["data"]});

        var lamdaResults = t1.Select().Join(
            t2.Select(), x => x["id"], y => y["id"],
            (x, y) => new {id=x["id"], name=x["data"], number=y["data"]});

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.

Alright all you mad lads out there, I think I've cracked it.

This is what I came up with for my problem, a bit of a pain in arse way of doing things, but it got the two datarows as one which is what I wanted.

Could not find anything as a default that did this, but please do let me know if it exists.

private DataRow JoinDataRow(DataRow r1, DataRow r2)
{
    // Get table columns
    var r1Cols = r1.Table.Columns;
    var r2Cols = r2.Table.Columns;

    // Create datatable to base row from
    var tempDataTable = new DataTable();
    foreach (DataColumn col in r1Cols)
    {
        tempDataTable.Columns.Add(new DataColumn(col.ColumnName, col.DataType, col.Expression, col.ColumnMapping));
    }

    foreach (DataColumn col in r2Cols)
    {
        tempDataTable.Columns.Add(new DataColumn(col.ColumnName, col.DataType, col.Expression, col.ColumnMapping));
    }

    // Create new return row to be returned
    DataRow returnRow = tempDataTable.NewRow();

    // Fill data
    int count = 0;
    for (int r1Index = 0; r1Index < r1Cols.Count; r1Index ++)
    {
        returnRow[r1Index] = r1[r1Index];
        count++;
    }

    for (int r2Index = count; r2Index < r2Cols.Count + count; r2Index++)
    {
        returnRow[r2Index] = r2[r2Index -count];
    }

    // Return row
    return returnRow;
}

An instance of how you could use it is perhaps using LINQ to join two separate data tables together and you want the rows to act accordingly, see example below:

var memberCompanyDetails = 
    (from DataRow member in members.Rows
    join DataRow company in companies.Rows on member["company"] equals company["company"]
    select JoinDataRow(member, company)).AsEnumerable().CopyToDataTable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM