join 2 datarow rows into one row C#

后端 未结 3 1622
不知归路
不知归路 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:47

    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();
    

提交回复
热议问题