如何使用列名称的值来获取列?

时间:2017-07-15 12:43:04

标签: c# datatable

我想从datatable中取一些列然后复制到另一个数据表。 这可能吗? 例如;我想获取ID和Name列及其行值。

        DataTable table = new DataTable();
        table.Columns.Add("ID");
        table.Columns.Add("Name");
        table.Columns.Add("Surname");
        table.Rows.Add("1", "Mike","Zt");
        table.Rows.Add("2", "Richard", "Milko");
        table.Rows.Add("3", "Sumo", "Sansimo");

2 个答案:

答案 0 :(得分:1)

有一种非常简单的方法可以做你想要的事情

DataTable table = new DataTable();
table.Columns.Add("ID");
table.Columns.Add("Name");
table.Columns.Add("Surname");
table.Rows.Add("1", "Mike","Zt");
table.Rows.Add("2", "Richard", "Milko");
table.Rows.Add("3", "Sumo", "Sansimo");

DataTable newTable = table.DefaultView.ToTable(false, new string[] {"ID", "Name"});
foreach(DataRow r in newTable.Rows)
        Console.WriteLine("ID=" + r.Field<string>("ID") + ", Name=" + r.Field<string>("Name"));

答案 1 :(得分:0)

修改1:

将列(ID,名称)及其行数据从一个DataTable(表)复制到另一个DataTable(table2)。

// create new table to which you want copy the first table
DataTable table2 = new DataTable();

// now copy the columns (ID,Name) from table to table2
foreach (DataColumn column in table.Columns)
{
    if(column.ColumnName == "ID" || column.ColumnName == "Name")
        table2.Columns.Add(column.ColumnName);
}

// copy the all data of columns (ID,Name) from table to table2
foreach (DataRow row in table.Rows)
{
    // initialize the new row for your data
    List<string> rowData = new List<string>();

    // add your columns (ID,Name) data to the new row
    foreach (DataColumn column in table.Columns)
    {
        if(column.ColumnName == "ID" || column.ColumnName == "Name")
            rowData.Add(row[column.ColumnName].ToString());
    }

    // add the data row to the new DataTable (table2)
    table2.Rows.Add(rowData);
}