Create a Pivot Table from a DataTable

后端 未结 4 1921
耶瑟儿~
耶瑟儿~ 2021-02-07 23:53

I am using C# winforms to create an application that needs to turn a datatable into a pivot table. I have the pivot table working fine from a SQL end, but creating it from a da

4条回答
  •  悲&欢浪女
    2021-02-08 00:31

    Learn the hash-pivot tesuji:

    var inDT = new DataTable();
    // Fill the input table
    
    var oDT = new DataTable();
    var dfq = new Dictionary;
    oDT.Columns.Add("StartDateTime", typeof(DateTime));
    for (int i = 0; i < inDT.Rows.Count; i++) {
        var key = (DateTime)inDT.Rows[i][0];
        var row = (String)inDT.Rows[i][2];
        var data = (Double)inDT.Rows[i][1];
    
        if (!oDT.Columns.Contains(row)) {
           oDT.Columns.Add(row);
        }
        if (dfq.ContainsKey(key)) {
            dfq[key][row] = data;
        } else {
            var oRow = oDT.NewRow();
            oRow[0] = key;
            oRow[row] = data;
            dfq.Add(key, oRow);
            oDT.Rows.Add(oRow);
        }
    }
    // pivot table in oDT
    

提交回复
热议问题