Join multiple DataRows into a single DataRow

前端 未结 4 1725
轻奢々
轻奢々 2021-01-26 09:15

I am writing this in C# using .NET 3.5. I have a System.Data.DataSet object with a single DataTable that uses the following schema:

Id      :  uint
AddressA:  s         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 09:58

    I agree with Steven that the best way to do this is to do it in the database. But if that isn't an option you can try the following:

    • Make a new datatable and add the columns you need manually using DataTable.Columns.Add(name, datatype)
    • Step through the first datatables Rows collection and for each row create a new row in your new datatable using DataTable.NewRow()
    • Copy the values of the columns found in the first table into the new row
    • Find the matching row in the other data table using Select() and copy out the final value into the new data row
    • Add the row to your new data table using DataTable.Rows.Add(newRow)

    This will give you a new data table containing the combined data from the two tables. It won't be very fast, but unless you have huge amounts of data it will probably be fast enough. But try to avoid doing a LIKE-query in the Select, for that one is slow.

    One possible optimization would be possible if both tables contains rows with identical primary keys. You could then sort both tables and step through them fetching both data rows using their array index. This would rid you of the Select call.

提交回复
热议问题