分组方法DynamicLinqExtensions:
/// <summary> /// 动态构建分组表达式 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="propertyNames">上限最大7个元素</param> /// <returns></returns> public static Expression<Func<T, object>> GroupByExpression<T>(string[] propertyNames) { var properties = propertyNames.Select(name => typeof(T).GetProperty(name)).ToArray(); var propertyTypes = properties.Select(p => p.PropertyType).ToArray(); var tupleTypeDefinition = typeof(Tuple).Assembly.GetType("System.Tuple`" + properties.Length); var tupleType = tupleTypeDefinition.MakeGenericType(propertyTypes); var constructor = tupleType.GetConstructor(propertyTypes); var param = Expression.Parameter(typeof(T), "item"); var body = Expression.New(constructor, properties.Select(p => Expression.Property(param, p))); var expr = Expression.Lambda<Func<T, object>>(body, param); return expr; } /// <summary> /// 动态分组 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="propertyNames">任意个数元素</param> /// <returns></returns> public static IEnumerable<IGrouping<object[], T>> GroupByDynamic<T>(this IEnumerable<T> source, params string[] propertyNames) { var parameter = Expression.Parameter(typeof(T), "item"); var projections = propertyNames.Select(propertyName => Expression.PropertyOrField(parameter, propertyName) ).ToArray(); var body = Expression.NewArrayInit(typeof(object), projections.Cast<Expression>()); var lambda = Expression.Lambda<Func<T, object[]>>(body, parameter); return source.GroupBy(lambda.Compile(), new ObjectArrayComparer()); }
// 自定义比较器,用于比较object数组 public class ObjectArrayComparer : IEqualityComparer<object[]> { public bool Equals(object[] x, object[] y) { if (x == null && y == null) return true; if (x == null || y == null) return false; if (x.Length != y.Length) return false; for (int i = 0; i < x.Length; i++) { if (!Equals(x[i], y[i])) return false; } return true; } public int GetHashCode(object[] obj) { unchecked { int hash = 17; foreach (var item in obj) { if (item != null) { hash = hash * 23 + item.GetHashCode(); } } return hash; } } }View Code
标签:return,C#,public,item,分组,var,Expression,多字段 From: https://www.cnblogs.com/SmilePastaLi/p/18361147