简体   繁体   English

从DataTable中删除列表中不存在的行

[英]Remove rows from DataTable that do not exist in a list

I have a dynamic list that contains the names of columns 我有一个包含列名称的动态列表

 var newList = new List<string>(){ "ColName1", "ColName2", "ColName3", "ColName4" };

I also have a datatable that has these column names. 我还有一个具有这些列名称的数据表。 However this datatable needs to match my list so if there are columns in this datatable that do not exist in the list then it needs to be removed. 但是,此数据表需要与我的列表匹配,因此如果此数据表中的列在列表中不存在,则需要将其删除。 How can I do that? 我怎样才能做到这一点? So far this is what i have 到目前为止,这就是我所拥有的

      DataTable sourceData = new DataTable();
      List<DataRow> rowsToDelete = new List<DataRow>();

                foreach (DataRow row in sourceData.Rows)
                {
                    if (!newList.Contains(row[""].ToString())) //Errors here as the names cannot be hardcoded. It needs to be dynamic
                    {
                        rowsToDelete.Add(row);
                    }
                }

                foreach (DataRow row in rowsToDelete)
                {
                    sourceData.Rows.Remove(row);
                }

                sourceData.AcceptChanges();

You could simply remove them like: 你可以简单地删除它们,如:

foreach(string col in newList)
    if(sourceData.Columns.Contains(col))
         sourceData.Columns.Remove(col);

But however it's better not to include them in your query in the first place: 但是最好不要首先将它们包含在您的查询中:

string query = $"select {string.Join(",", newList)} from someTable";

I'm not sure why you're checking if columns exist on a DataRow , they are defined on the DataTable , but this would work: 我不确定你为什么要检查DataRow上是否存在列,它们是在DataTable上定义的,但是这可行:

if (row.Table.Columns.Cast<DataColumn>().Any(x => !newList.Contains(x.ColumnName)))
{
    rowsToDelete.Add(row);
}

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

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