-4

我有一个包含两列的数据表(第 1 列 - 表名称,第 2 列 - 列名称),即

Table_Name | Columns_Name |

SALES --------------   PROD_ID

SALES ----------------   SALES_ID

CUSTOMER ---------   CUST_ID

CUSTOMER ---------- CUST_NAME 

PRODUCT   ------------ PRODUCT_ID

PRODUCT   ------------ PRODUCT_NAME

我想通过在不同的列中添加每个 TableName 和相关字段来重组数据(使用现有的 DataTable 或通过创建新的 DataTable),即

Table_Name1 | Columns_Name1 |     Table_Name2 | Columns_Name2 |    Table_Name3 | Columns_Name3 |

SALES --------------   PROD_ID   | -----|CUSTOMER ---------   CUST_ID  | ------- |  PRODUCT   ------------ PRODUCT_ID



SALES ----------------   SALES_ID |------ |CUSTOMER ---------   CUST_NAME  | ------ |   PRODUCT   -------- PRODUCT_NAME  

主 DataTable 将使用不同的 TableNames 和 ColumnNames 动态填充。您能否纠正一个示例代码/循环,它将获取具有相关字段的每个表并将它们按顺序放在不同的列中。

4

1 回答 1

-1
class Program
{
    static void Main(string[] args)
    {
        DataTable table = new DataTable();
        table.Columns.Add("Table_Name", typeof(string));
        table.Columns.Add("Column_Name", typeof(string));

        table.Rows.Add("SALES   ", "PROD_ID     ");
        table.Rows.Add("SALES   ", "SALES_ID    ");
        table.Rows.Add("CUSTOMER", "CUST_ID     ");
        table.Rows.Add("CUSTOMER", "CUST_NAME   ");
        table.Rows.Add("PRODUCT ", "PRODUCT_ID  ");
        table.Rows.Add("PRODUCT ", "PRODUCT_NAME");

        DataTable newTable = RotateDataTable(table, 0);

        foreach (DataRow dataRow in newTable.Rows)
        {
            foreach (var item in dataRow.ItemArray)
            {
                Console.Write("#" + item + "# ");
            }
            Console.WriteLine();
        }
    }

    private static DataTable RotateDataTable(DataTable table, int groupingColumn)
    {

        var grouped = table.AsEnumerable()
                .GroupBy(dr => dr.ItemArray[groupingColumn])
                .Select(grouping => grouping.ToList())
                .ToList();
        int count = grouped.Count;
        int rowCount = grouped[0].Count;
        if (!grouped.All(g => g.Count == rowCount))
            throw new Exception("Unexpected input");


        DataTable newTable = new DataTable();

        for (int i = 0; i < count; i++)
        {
            for (int j = 0; j < table.Columns.Count; j++)
                newTable.Columns.Add(table.Columns[j].ColumnName + (i + j));
        }

        for (int i = 0; i < rowCount; i++)
            newTable.Rows.Add(newTable.NewRow());

        for (int i = 0; i < count; i++)
        {
            var list = grouped[i].ToList();
            for (int j = 0; j < rowCount; j++)
            {
                for (int k = 0; k < list[j].ItemArray.Length; k++)
                {
                    string field = list[j].Field<string>(k);
                    int index = (i * table.Columns.Count) + k;
                    newTable.Rows[j].SetField<string>(index, field);
                }
            }
        }
        return newTable;
    }
}
于 2013-10-07T16:01:11.180 回答