I have a scenario where I get a data table with 65 columns and 100 rows. I need to create one more data table with all 100 rows, i.e. the same as the original data table but should be having only 5 columns out of 65 present in original table. Is there any way to achieve this without looping?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Try DataView.ToTable method.
Use it like this:
DataTable newTable = oldTable.DefaultView.ToTable(false, "ColumnName1", "ColumnName2", "ColumnName3", "ColumnName4", "ColumnName5");
回答2:
DataTable oldTable = new DataTable();
DataTable newTable = oldTable.Copy();
for (int i = 5; i < 65; i++)
{
newTable.Columns.RemoveAt(i);
}
回答3:
Try like this,
DataTable newTable = oldTable.Copy();
newTable.Columns.Remove("ColumnName");
You remove the unwanted columns here.
Here is the best Solution for your Question:
DataTable dt = new DataTable();
string [] column = {"Column1", "Column2"};
dt = DTItem.DefaultView.ToTable("dd", false, column);
//DTItem is the Existing Table and "dd" is the temporary tablename, u give whatever u want
回答4:
private void button3_Click(object sender, EventArgs e)
{
DataTable destiny = new DataTable();
destiny.Columns.Add("c1");
destiny.Columns.Add("c2");
destiny.Columns.Add("c3");
destiny.Columns.Add("c4");
CopyColumns(dtST_Split, destiny, "c1", "c2","c3","c4");
}
private void CopyColumns(DataTable source, DataTable dest, params string[] columns)
{
foreach (DataRow sourcerow in source.Rows)
{
DataRow destRow = dest.NewRow();
foreach (string colname in columns)
{
destRow[colname] = sourcerow[colname];
}
dest.Rows.Add(destRow);
}
}