简体   繁体   English

比较C#中两个DataTable的列名

[英]Compare Columns name of Two DataTable in C#

I have two datatables,我有两个数据表,

  1. dtSchema datatable filled by ms-access database由 ms-access 数据库填充的dtSchema数据表
  2. table datatable filled by excel sheet table数据表由 excel 表填充

table must have four columns named (SN, FN, DOB, Sec) table必须有四列命名为(SN、FN、DOB、Sec)

I want to compare the columns name of table with columns name of dtSchema .我想将table的列名与dtSchema的列名进行比较。 The columns in table which are not matched with dtSchema place them in list. table中与dtSchema不匹配的列将它们放入列表中。

foreach (DataColumn col in table.Columns)
{
       isColumnMatch = false;
       foreach(DataColumn colDb in dtSchema.Columns)
       {
             if(col.ColumnName == colDb.ColumnName)
             {
             }
       }

} }

I can compare the datatables column name.我可以比较数据表的列名。 If table above four columns matched with dtSchema and the table has more than four columns then columns which are not matched must be placed in list.如果table上面的四列与dtSchema匹配并且table有超过四列,那么不匹配的列必须放在列表中。

It can be achieved by a simple LINQ query, something like:它可以通过一个简单的 LINQ 查询来实现,类似于:

var tableColumnNames = table.Columns.Cast<DataColumn>().Select(c=>c.ColumnName).ToList();
var schemaColumnNames = dtSchema.Columns.Cast<DataColumn>().Select(c=>c.ColumnNames).ToList();

var unmatchedColumnNames = 
    from col in tableColumnNames where !schemaColumnNames.Contains(col) select col;

For this, you need to use any collection to save all those columns that are not matched so in case if columnName or title is not matched then you have to push it to some list.为此,您需要使用任何集合来保存所有那些不匹配的列,以防万一 columnName 或 title 不匹配,那么您必须将其推送到某个列表。 So at the end, you will have a list of unmatched columns所以最后,您将得到一个不匹配列的列表

===== Updated ====== =====更新了======

var filter= from firstDt in dt1.AsEnumerable()
        where !(from secondDt in dt2.AsEnumerable() select secondDt["Name"]).Contains(firstDt["Name"].ToString()) select firstDt; DataTable resultDt = filter.CopyToDataTable();

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

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