C#List实现⾏转列的通⽤⽅案
最近在做报表统计⽅⾯的需求,涉及到⾏转列报表。根据以往经验使⽤SQL可以⽐较容易完成,这次决定挑战⼀下直接通过代码⽅式完成⾏转列。期间遇到⼏个问题和⽤到的新知识这⾥整理记录⼀下。
阅读⽬录
问题介绍
动态Linq
System.Linq.Dynamic其它⽤法typeof的用法
总结
问题介绍
以家庭⽉度费⽤为例,可以在[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.9302516724.517.9
李四56.724.713.265.218.914.9
区域-⽉明细报表
户主姓名
2016-012016-02
电费⽔费燃⽓费电费⽔费燃⽓费
江夏区2240.93304255167264.5177.9
洪⼭区576.7264.7173.2665.2108.9184.9
区域⽉份-户明细报表
区域⽉份
张三李四
燃⽓费电费⽔费燃⽓费电费⽔费
江夏区2016-012240.93304255167264.5177.9洪⼭区2016-01576.7264.7173.2665.2108.9184.9江夏区2016-023240.94305256167364.5277.9洪⼭区2016-02676.7364.7273.2765.2208.9284.9
洪⼭区2016-02676.7364.7273.2765.2208.9284.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);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。