动态分组:
public static class DynamicLinqExtensions { /// <summary> /// 分组查询 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">数据源</param> /// <param name="groupingSelectorKeys">动态指定的列</param> /// <param name="groupingKeySelector">所有列的 Lambda 表达式集合</param> /// <returns></returns> public static IEnumerable<Group<T>> GroupBy<T>(this IEnumerable<T> source, IEnumerable<string> groupingSelectorKeys, Dictionary<string, Func<T, object>> groupingKeySelector) { var groupedResult = Enumerable.Empty<Group<T>>(); if (groupingSelectorKeys.Any()) { string selectorType = groupingSelectorKeys.First(); var selector = groupingKeySelector[selectorType]; IEnumerable<string> nextSelectorTypes = groupingSelectorKeys.Skip(1); groupedResult = source.GroupBy(selector).Select(group => { Group<T> newGroup = new Group<T> { Type = selectorType, Value = group.Key?.ToString(), Items = group.Select(x => x), }; newGroup.SubGroup = group.GroupBy(nextSelectorTypes, groupingKeySelector); return newGroup; }); } return groupedResult; } }View Code
Dictionary<string, Func<VOIODashboardDto, object>> groupingKeySelector = new Dictionary<string, Func<VOIODashboardDto, object>>(); groupingKeySelector["Brand"] = x => x.Brand; groupingKeySelector["Category"] = x => x.Category; // 定义要根据哪些属性进行分组 string[] groupByProperties = { "Category", "Brand" }; var groupList = list.GroupBy(groupByProperties, groupingKeySelector);
标签:groupingKeySelector,group,groupingSelectorKeys,C#,IEnumerable,List,分组,GroupBy From: https://www.cnblogs.com/SmilePastaLi/p/18123968