zoukankan      html  css  js  c++  java
  • C#List实现行转列

      最近在做报表统计方面的需求,涉及到行转列报表。根据以往经验使用SQL可以比较容易完成,这次决定挑战一下直接通过代码方式完成行转列。期间遇到几个问题和用到的新知识这里整理记录一下。

    阅读目录

    问题介绍

      以家庭月度费用为例,可以在[Name,Area,Month]三个维度上随意组合进行分组,三个维度中选择一个做为列显示。

    复制代码
        /// <summary>
        /// 家庭费用情况
        /// </summary>
        public class House
        {
            /// <summary>
            /// 户主姓名
            /// </summary>
            public string Name { get; set; }
    
            /// <summary>
            /// 所属行政区域
            /// </summary>
            public string Area { get; set; }
    
            /// <summary>
            /// 月份
            /// </summary>
            public string Month { get; set; }
    
            /// <summary>
            /// 电费金额
            /// </summary>
            public double DfMoney { get; set; }
    
            /// <summary>
            /// 水费金额
            /// </summary>
            public double SfMoney { get; set; }
    
            /// <summary>
            /// 燃气金额
            /// </summary>
            public double RqfMoney { get; set; }
        }
    复制代码
    户主-月明细报表
    户主姓名2016-012016-02
    电费水费燃气费电费水费燃气费
    张三 240.9 30 25 167 24.5 17.9
    李四 56.7 24.7 13.2 65.2 18.9 14.9
    区域-月明细报表
    户主姓名2016-012016-02
    电费水费燃气费电费水费燃气费
    江夏区 2240.9 330 425 5167 264.5 177.9
    洪山区 576.7 264.7 173.2 665.2 108.9 184.9
    区域月份-户明细报表
    区域月份张三李四
    燃气费电费水费燃气费电费水费
    江夏区 2016-01 2240.9 330 425 5167 264.5 177.9
    洪山区 2016-01 576.7 264.7 173.2 665.2 108.9 184.9
    江夏区 2016-02 3240.9 430 525 6167 364.5 277.9
    洪山区 2016-02 676.7 364.7 273.2 765.2 208.9 284.9
      
      现在后台查出来的数据是List<House>类型,前台传过来分组维度和动态列字段。
      第1个表格前台传给后台参数
    {DimensionList:['Name'],DynamicColumn:'Month'}

     第2个表格前台传给后台参数

    {DimensionList:['Area'],DynamicColumn:'Month'}
    第3个表格前台传给后台参数
    {DimensionList:['Area','Month'],DynamicColumn:'Name'}
    问题描述清楚后,仔细分析后你就会发现这里的难题在于动态分组,也就是怎么根据前台传过来的多个维度对List进行分组。
     

    动态Linq

       下面使用System.Linq.Dynamic完成行转列功能,Nuget上搜索System.Linq.Dynamic即可下载该包。

       代码进行了封装,实现了通用的List<T>行转列功能。

    复制代码
            /// <summary>
            /// 动态Linq方式实现行转列
            /// </summary>
            /// <param name="list">数据</param>
            /// <param name="DimensionList">维度列</param>
            /// <param name="DynamicColumn">动态列</param>
            /// <returns>行转列后数据</returns>
            private static List<dynamic> DynamicLinq<T>(List<T> list, List<string> DimensionList, string DynamicColumn, out List<string> AllDynamicColumn) where T : class
            {
                //获取所有动态列
                var columnGroup = list.GroupBy(DynamicColumn, "new(it as Vm)") as IEnumerable<IGrouping<dynamic, dynamic>>;
                List<string> AllColumnList = new List<string>();
                foreach (var item in columnGroup)
                {
                    if (!string.IsNullOrEmpty(item.Key))
                    {
                        AllColumnList.Add(item.Key);
                    }
                }
                AllDynamicColumn = AllColumnList;
                var dictFunc = new Dictionary<string, Func<T, bool>>();
                foreach (var column in AllColumnList)
                {
                    var func = DynamicExpression.ParseLambda<T, bool>(string.Format("{0}=="{1}"", DynamicColumn, column)).Compile();
                    dictFunc[column] = func;
                }
    
                //获取实体所有属性
                Dictionary<string, PropertyInfo> PropertyInfoDict = new Dictionary<string, PropertyInfo>();
                Type type = typeof(T);
                var propertyInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                //数值列
                List<string> AllNumberField = new List<string>();
                foreach (var item in propertyInfos)
                {
                    PropertyInfoDict[item.Name] = item;
                    if (item.PropertyType == typeof(int) || item.PropertyType == typeof(double) || item.PropertyType == typeof(float))
                    {
                        AllNumberField.Add(item.Name);
                    }
                }
    
                //分组
                var dataGroup = list.GroupBy(string.Format("new ({0})", string.Join(",", DimensionList)), "new(it as Vm)") as IEnumerable<IGrouping<dynamic, dynamic>>;
                List<dynamic> listResult = new List<dynamic>();
                IDictionary<string, object> itemObj = null;
                T vm2 = default(T);
                foreach (var group in dataGroup)
                {
                    itemObj = new ExpandoObject();
                    var listVm = group.Select(e => e.Vm as T).ToList();
                    //维度列赋值
                    vm2 = listVm.FirstOrDefault();
                    foreach (var key in DimensionList)
                    {
                        itemObj[key] = PropertyInfoDict[key].GetValue(vm2);
                    }
    
                    foreach (var column in AllColumnList)
                    {
                        vm2 = listVm.FirstOrDefault(dictFunc[column]);
                        if (vm2 != null)
                        {
                            foreach (string name in AllNumberField)
                            {
                                itemObj[name + column] = PropertyInfoDict[name].GetValue(vm2);
                            }
                        }
                    }
                    listResult.Add(itemObj);
                }
                return listResult;
            }
    复制代码

       

       标红部分使用了System.Linq.Dynamic动态分组功能,传入字符串即可分组。使用了dynamic类型,关于dynamic介绍可以参考其它文章介绍哦。

    System.Linq.Dynamic其它用法

        上面行转列代码见识了System.Linq.Dynamic的强大,下面再介绍一下会在开发中用到的方法。

        Where过滤

    list.Where("Name=@0", "张三")

    上面用到了参数化查询,实现了查找姓名是张三的数据,通过这段代码你或许感受不到它的好处。但是和EntityFramework结合起来就可以实现动态拼接SQL的功能了。
    复制代码
            /// <summary>
            /// EF实体查询封装 
            /// </summary>
            /// <typeparam name="T">实体类型</typeparam>
            /// <param name="Query">IQueryable对象</param>
            /// <param name="gridParam">过滤条件</param>
            /// <returns>查询结果</returns>
            public static EFPaginationResult<T> PageQuery<T>(this IQueryable<T> Query, QueryCondition gridParam)
            {
                //查询条件
                EFFilter filter = GetParameterSQL<T>(gridParam);
                var query = Query.Where(filter.Filter, filter.ListArgs.ToArray());
                //查询结果
                EFPaginationResult<T> result = new EFPaginationResult<T>();
                if (gridParam.IsPagination)
                {
                    int PageSize = gridParam.PageSize;
                    int PageIndex = gridParam.PageIndex < 0 ? 0 : gridParam.PageIndex;
                    //获取排序信息
                    string sort = GetSort(gridParam, typeof(T).FullName);
                    result.Data = query.OrderBy(sort).Skip(PageIndex * PageSize).Take(PageSize).ToList<T>();
                    if (gridParam.IsCalcTotal)
                    {
                        result.Total = query.Count();
                        result.TotalPage = Convert.ToInt32(Math.Ceiling(result.Total * 1.0 / PageSize));
                    }
                    else
                    {
                        result.Total = result.Data.Count();
                    }
                }
                else
                {
                    result.Data = query.ToList();
                    result.Total = result.Data.Count();
                }
                return result;
            }
    复制代码
    复制代码
    /// <summary>
            /// 通过查询条件,获取参数化查询SQL
            /// </summary>
            /// <param name="gridParam">过滤条件</param>
            /// <returns>过滤条件字符</returns>
            private static EFFilter GetParameterSQL<T>(QueryCondition gridParam)
            {
                EFFilter result = new EFFilter();
                //参数值集合
                List<object> listArgs = new List<object>();
                string filter = "1=1";
    
                #region "处理动态过滤条件"
                if (gridParam.FilterList != null && gridParam.FilterList.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
    
                    int paramCount = 0;
                    DateTime dateTime;
                    //操作符
                    string strOperator = string.Empty;
                    foreach (var item in gridParam.FilterList)
                    {
                        //字段名称为空则跳过
                        if (string.IsNullOrEmpty(item.FieldName))
                        {
                            continue;
                        }
                        //匹配枚举,防止SQL注入
                        Operator operatorEnum = (Operator)Enum.Parse(typeof(Operator), item.Operator, true);
    
                        //跳过字段值为空的
                        if (operatorEnum != Operator.Null && operatorEnum != Operator.NotNull && string.IsNullOrEmpty(item.FieldValue))
                        {
                            continue;
                        }
                        strOperator = operatorEnum.GetDescription();
                        if (item.IgnoreCase && !item.IsDateTime)
                        {
                            //2016-07-19添加查询时忽略大小写比较
                            item.FieldValue = item.FieldValue.ToLower();
                            item.FieldName = string.Format("{0}.ToLower()", item.FieldName);
                        }
                        switch (operatorEnum)
                        {
                            //等于,不等于,小于,大于,小于等于,大于等于
                            case Operator.EQ:
                            case Operator.NE:
                            case Operator.GT:
                            case Operator.GE:
                            case Operator.LT:
                            case Operator.LE:
                                if (item.IsDateTime)
                                {
                                    if (DateTime.TryParse(item.FieldValue, out dateTime))
                                    {
                                        if (!item.FieldValue.Contains("00:00:00") && dateTime.ToString("HH:mm:ss") == "00:00:00")
                                        {
                                            if (operatorEnum == Operator.LE)
                                            {
                                                listArgs.Add(DateTime.Parse(dateTime.ToString("yyyy-MM-dd") + " 23:59:59"));
                                            }
                                            else
                                            {
                                                listArgs.Add(dateTime);
                                            }
                                        }
                                        else
                                        {
                                            listArgs.Add(dateTime);
                                        }
                                        sb.AppendFormat(" AND {0} {1} @{2}", item.FieldName, strOperator, paramCount);
                                    }
                                }
                                else
                                {
                                    listArgs.Add(ConvertToType(item.FieldValue, GetPropType<T>(item.FieldName)));
                                    sb.AppendFormat(" AND {0} {1} @{2}", item.FieldName, strOperator, paramCount);
                                }
                                paramCount++;
                                break;
                            case Operator.Like:
                            case Operator.NotLike:
                            case Operator.LLike:
                            case Operator.RLike:
                                listArgs.Add(item.FieldValue);
                                if (operatorEnum == Operator.Like)
                                {
                                    sb.AppendFormat(" AND {0}.Contains(@{1})", item.FieldName, paramCount);
                                }
                                else if (operatorEnum == Operator.NotLike)
                                {
                                    sb.AppendFormat(" AND !{0}.Contains(@{1})", item.FieldName, paramCount);
                                }
                                else if (operatorEnum == Operator.LLike)
                                {
                                    sb.AppendFormat(" AND {0}.EndsWith(@{1})", item.FieldName, paramCount);
                                }
                                else if (operatorEnum == Operator.RLike)
                                {
                                    sb.AppendFormat(" AND {0}.StartsWith(@{1})", item.FieldName, paramCount);
                                }
                                paramCount++;
                                break;
                            case Operator.Null:
                                listArgs.Add(item.FieldValue);
                                sb.AppendFormat(" AND {0}=null", item.FieldName);
                                paramCount++;
                                break;
                            case Operator.NotNull:
                                listArgs.Add(item.FieldValue);
                                sb.AppendFormat(" AND {0}!=null", item.FieldName);
                                paramCount++;
                                break;
                            case Operator.In:
                                sb.AppendFormat(" AND (");
                                foreach (var schar in item.FieldValue.Split(','))
                                {
                                    listArgs.Add(schar);
                                    sb.AppendFormat("{0}=@{1} or ", item.FieldName, paramCount);
                                    paramCount++;
                                }
                                sb.Remove(sb.Length - 3, 3);
                                sb.AppendFormat(" )");
                                break;
                            case Operator.NotIn:
                                sb.AppendFormat(" AND (");
                                foreach (var schar in item.FieldValue.Split(','))
                                {
                                    listArgs.Add(schar);
                                    sb.AppendFormat("{0}!=@{1} and ", item.FieldName, paramCount);
                                    paramCount++;
                                }
                                sb.Remove(sb.Length - 3, 3);
                                sb.AppendFormat(" )");
                                break;
                        }
                        if (sb.ToString().Length > 0)
                        {
                            filter = sb.ToString().Substring(4, sb.Length - 4);
                        }
                    }
                    #endregion
    
                }
                result.Filter = filter;
                result.ListArgs = listArgs;
                return result;
            }
    复制代码
     

    总结

          本篇通过行转列引出了System.Linq.Dynamic,并且介绍了过滤功能,其实它的用处还有很多,等待大家发掘。下面给出本文示例代码:DynamicLinq

  • 相关阅读:
    <trim>: prefix+prefixOverrides+suffix+suffixOverrides
    时间js
    form表单中name和id区别
    SQL 递归
    表单中Readonly和Disabled的区别
    jquery select取值,赋值操作
    ie11
    mongodb 学习资料
    H5 限制input只能输入数字
    http头部解释
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/6497742.html
Copyright © 2011-2022 走看看