• C# DataTable 行转列


    原数据结构:

    转换后数据结构:

    当然可以移除不必要的列:如:FNetCostAmount ,移除方法很简单,

    //参数肯定是数据源啦。

    DataTable dt = RowToCol(newDt);


    dt.Columns.Remove("FNetCostAmount");

    private DataTable RowToCol(DataTable dataSource)
            {
                //读取所需列内所有行数据
                DataTable newDataTable = dataSource;
                //维度:1、列标题名   2、⒈行坐标 ⒉行内值
                Dictionary<string, Dictionary<int, string>> myDictionary = new Dictionary<string, Dictionary<int, string>>();
                for (int i = 0; i < newDataTable.Rows.Count; i++)
                {
                    if (!myDictionary.ContainsKey(newDataTable.Rows[i]["FBrandGroupname"].ToString()))
                    {
                        Dictionary<int, string> myIndex = new Dictionary<int, string>();
                        myIndex.Add(i, newDataTable.Rows[i]["FNetCostAmount"].ToString());
                        myDictionary.Add(newDataTable.Rows[i]["FBrandGroupname"].ToString(), myIndex);
                    }
                    else
                    {
                        myDictionary[newDataTable.Rows[i]["FBrandGroupname"].ToString()].Add(i, newDataTable.Rows[i]["FNetCostAmount"].ToString());
                    }
                }
                newDataTable.Columns.Remove("FBrandGroupname");
                foreach (string key in myDictionary.Keys)
                {
                    newDataTable.Columns.Add(key);
                    foreach (KeyValuePair<int, string> item in myDictionary[key.ToString(CultureInfo.InvariantCulture)])
                    {
                        newDataTable.Rows[item.Key][key] = item.Value;
                    }
                }
                return newDataTable;

            }

    不懂的,自己打断点看数据格式。

  • 相关阅读:
    Codeforces 525C Om Nom and Candies 枚举 + 复杂度分析
    Codeforces 526B Om Nom and Dark Park 树形dp
    Codeforces 526A King of Thieves 枚举
    Regionals 2014 Asia
    Regionals 2014 Asia
    access数据库和sqlsever数据库sql语句的布尔值boolean的写法
    取消阴影行
    引用其他单元的2种方法
    选中阴影行
    全选
  • 原文地址:https://www.cnblogs.com/IThefeng/p/3196296.html
Copyright © 2020-2023  润新知