C#行列转换(交叉表)处理源代码

        /// <summary>
        /// 将DataTable的第二列的值转化为列(即将原来的行表,转化成交叉表,没有对应值则默认0)贾世义
        /// </summary>
        /// <param name="dt">必须三列,第三列为值</param>
        /// <returns></returns>
        public static DataTable GetCrossTable(DataTable dt)
        {
            if (dt == null || dt.Columns.Count != 3 || dt.Rows.Count == 0)
            {
                return dt;
            }
            else
            {
                DataTable result = new DataTable();
                result.Columns.Add(dt.Columns[0].ColumnName, dt.Columns[2].DataType);
                DataTable dtColumns = dt.DefaultView.ToTable("dtColumns", true, dt.Columns[1].ColumnName);
                foreach (DataRow drColumnsRow in dtColumns.Select("", dt.Columns[1].ColumnName))
                {
                    string colName = GetValue(drColumnsRow[0]);
                    if (String.IsNullOrEmpty(colName))
                    {
                        colName = "无列名";
                    }
                    result.Columns.Add(colName);
                    result.Columns[result.Columns.Count - 1].DefaultValue = 0;
                }
                DataRow drNew = result.NewRow();
                drNew[0] = dt.Rows[0][0];
                string rowName = drNew[0].ToString();
                foreach (DataRow dr in dt.Rows)
                {
                    string colName = dr[1].ToString();
                    if (rowName.Equals(dr[0].ToString(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        drNew[colName] = dr[2];
                    }
                    else
                    {
                        result.Rows.Add(drNew);
                        drNew = result.NewRow();
                        drNew[0] = dr[0];
                        rowName = drNew[0].ToString();
                        drNew[colName] = dr[2];
                    }
                }
                result.Rows.Add(drNew);
                return result;
            }
        }

欢迎访问:http://121.18.78.216 适易查询分析、工作流、内容管理及项目管理演示平台

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jsyhello/article/details/6889439
个人分类: 技术
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭