简体   繁体   English

将数据表行从一个表复制到另一个表

[英]copy datatable rows from one table to another

queryDataTable has the data within it and if the check is true that the row contrains that word it add that whole row to the extractedData .. but at the moment there is only two rows to be added to the extractedData datatable but when I inspect the data there is 22 row added to it is there any reason for this the code is below queryDataTable包含其中的数据,如果该行包含该单词的检查为真,则它将整行添加到extractedData .. 但目前只有两行要添加到extractedData的数据数据表中,但是当我检查数据时有 22 行添加到它是否有任何原因代码如下

DataTable dt = new DataTable();

for (int k = 0; k < queryDataTable.Rows.Count; k++)
{

    string row = "";
    string test = queryDataTable.Rows[k][0].ToString();
    bool check = queryDataTable.Rows[k][0].ToString().StartsWith(queryString);
    if (check)
    {
        int errorcheck = k;
        extractedData.ImportRow(queryDataTable.Rows[errorcheck]);

    }
}

how would i only add a row at a certain index in the first datatable我如何只在第一个数据表中的某个索引处添加一行

If you want to check the entire row this code can't work, with this instruction:如果您想检查整行,则此代码不起作用,请使用以下说明:

queryDataTable.Rows[k][0].ToString().StartsWith(queryString);

you check only the first column of the k-row.您只检查 k 行的第一列。 First, you can use this more compact code:首先,您可以使用这个更紧凑的代码:

DataTable dt = new DataTable();
for (DataRow r in dt.Rows)
{
   if(r[0].startsWith(queryString))
   {
      extractedData.ImportRow(r);
   }
}

The if statament checks only the column 0 of each rows. if 语句只检查每行的第 0 列。 If you specify to me the check that you want to do i can try to modify this code or create a linq query.如果您向我指定要执行的检查,我可以尝试修改此代码或创建 linq 查询。

You can simply do this.你可以简单地做到这一点。 (StartsWith checks if a string startswith a substring). (StartsWith 检查字符串是否以子字符串开头)。

DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

var rows = table.AsEnumerable().Where(dr => dr.ItemArray.Contains("David"));

DataTable copyTable = new DataTable();
copyTable.Columns.Add("Dosage", typeof(int));
copyTable.Columns.Add("Drug", typeof(string));
copyTable.Columns.Add("Patient", typeof(string));
copyTable.Columns.Add("Date", typeof(DateTime));

foreach (var row in rows)
{
    copyTable.Rows.Add(row.ItemArray);
}

Sample data taken from https://www.dotnetperls.com/datatable样本数据取自https://www.dotnetperls.com/datatable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM