I have a DataRow like {"Foo", "Bar"} in a corresponding DataTable with 2 string columns. I want to copy this row to a new DataTable, which has 3 string columns, the 0th of which is a new value that I want to pass-in. So the resulting row should look like {"My", "Foo", "Bar"}.
Rinse, repeat. Another copy operation would go like {"Bob", "Smith"} => {"My", "Bob", "Smith"}.
I tried using the DataRow.ItemArray in an Array.Copy(), and myDataRow.ItemArray.CopyTo(otherDataRow.ItemArray) as well. Then I read that that doesn't work because the ItemArray is kinda Read-Only despite the intellisense telling you otherwise.
And of course I can write my own loop to copy the values column-by-column, but.. Why is this not built into the libraries or something?
Sample-code:
DataTable dtDestination = new DataTable();
DataTable dtSource = new DataTable();
dtSource.Columns.Add("Str1");
dtSource.Columns.Add("Str2");
dtDestination.Columns.Add("Str0");
dtDestination.Columns.Add("Str1");
dtDestination.Columns.Add("Str2");
dtSource.Rows.Add("Foo", "Bar");
dtSource.Rows.Add("Bob", "Smith");
foreach (DataRow drSrc in dtSource.Rows)
{
DataRow drNew = dtDestination.NewRow();
drNew["Str0"] = "My";
//this doesn't work
Array.Copy(drSrc.ItemArray, 0, drNew.ItemArray, 1, drSrc.ItemArray.Length);
//this doesn't work either
drSrc.ItemArray.CopyTo(drNew.ItemArray, 1);
//I want to add the "new row" to my destination table,
//*WITH* the contents from the source-row plus the "My" value in the 0th column!
dtDestination.Rows.Add(drNew);
}
drNew[1] = drSrc[0]; drNew[2] = drSrc[1]- Zer0DataRow.CopyValuesFrom(otherDataRow, startingIndex)or something. - NateJItemArrayis already created when you callNewRow. It's adding memory pressure producing more garbage for the GC. The accepted answer is creating 2 arrays per row. As for your example, what if I wanted to copy columns 1, 2 and 4? It's just too specific a use case and iterating is very simple to do. There's no real problem to solve here. - Zer0