C# List實現行轉列的通用方案。本站提示廣大學習愛好者:(C# List實現行轉列的通用方案)文章只能為提供參考,不一定能成為您想要的結果。以下是C# List實現行轉列的通用方案正文
最近在做報表統計方面的需求,涉及到行轉列報表。根據以往經驗使用SQL可以比較容易完成,這次決定挑戰一下直接通過代碼方式完成行轉列。期間遇到幾個問題和用到的新知識這裡整理記錄一下。
閱讀目錄
問題介紹 動態Linq System.Linq.Dynamic其它用法 總結問題介紹
以家庭月度費用為例,可以在[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; } }
戶主-月明細報表
區域-月明細報表
區域月份-戶明細報表
現在後台查出來的數據是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
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持!
[db:作者簡介][db:原文翻譯及解析]