如何在C#中修改数据表

问题描述

我是SSIS的新手,我从excel来源获取数据。 Excel源中有A,B,C,D,E,F之类的列。我创建了datatable1datatable1 contains columns A,D。现在,我想从工作表中的其余not in datatable1列中创建datatable2,但是它给了我错误Collection was modified; enumeration operation may not execute


DataTable datatable1 = new DataTable();
DataTable datatable2 = new DataTable();
DataTable datatable3 = new DataTable();
foreach (DataColumn tw in dataTable2.Columns) <--error shows here
{
if (datatable1.Columns.Contains(tw.ToString()))
{
dataTable2.Columns.Remove(tw);
}
datatable3.merge(datatable2)
}

解决方法

如错误所示,您无法修改要枚举的内容。

相反,枚举列的主列表。我给我的ref_data打了电话。对于找到的每一列,我问datatable1是否具有相同名称的列。如果是这样,我对Remove使用了datatable2方法来从集合中删除该列。

        DataTable ref_data = new DataTable();
        DataTable datatable1 = new DataTable();
        DataTable datatable2 = new DataTable();
        DataTable datatable3 = new DataTable();

        ref_data.Columns.Add(new DataColumn("A",System.Type.GetType("System.Int32")));
        ref_data.Columns.Add(new DataColumn("B",System.Type.GetType("System.Int32")));
        ref_data.Columns.Add(new DataColumn("C",System.Type.GetType("System.Int32")));
        ref_data.Columns.Add(new DataColumn("D",System.Type.GetType("System.Int32")));
        ref_data.Columns.Add(new DataColumn("E",System.Type.GetType("System.Int32")));
        ref_data.Columns.Add(new DataColumn("F",System.Type.GetType("System.Int32")));

        datatable1.Columns.Add(new DataColumn("A",System.Type.GetType("System.Int32")));
        datatable1.Columns.Add(new DataColumn("C",System.Type.GetType("System.Int32")));
        datatable1.Columns.Add(new DataColumn("D",System.Type.GetType("System.Int32")));

        // Duplicate datatable2 from ref_data
        // and then we'll remove what we don't need
        datatable2 = ref_data.Clone();

        // What columns exist in reference datatable that do not exist in datatable1?
        // Linq is probably more elegant but extensions are not working for me
        // var column_collection = ref_data.Columns.Where(x => x.)
        foreach (DataColumn item in ref_data.Columns)
        {
            // Build out datatable2 structure
            if (datatable1.Columns.Contains(item.ColumnName))
            {
                datatable2.Columns.Remove(item.ColumnName);
            }
        }

        // At this point,datatable 1 contains ACD,datatable2 contains BEF
        Console.WriteLine($"Dumping datatable1");
        foreach (DataColumn item in datatable1.Columns)
        {
            Console.WriteLine(item.ColumnName);
        }

        Console.WriteLine();
        Console.WriteLine($"Dumping datatable2");
        foreach (DataColumn item in datatable2.Columns)
        {
            Console.WriteLine(item.ColumnName);
        }