using System.Linq.Expressions; using System.Reflection; namespace YLErp.Helpers { /// /// 合计帮助类 /// public static class SumHelper { /// /// 属性合计 /// public static Dictionary CalculateSums(IEnumerable list) where T : class { var type = typeof(T); var sum = new Dictionary(); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (property.PropertyType != typeof(int) && property.PropertyType != typeof(long) && property.PropertyType != typeof(decimal) && property.PropertyType != typeof(double) && property.PropertyType != typeof(int?) && property.PropertyType != typeof(long?) && property.PropertyType != typeof(decimal?) && property.PropertyType != typeof(double?)) { continue; } var parameter = Expression.Parameter(typeof(T), string.Empty); var source = Expression.Constant(list, typeof(IEnumerable)); var member = Expression.PropertyOrField(parameter, property.Name); var lambda = Expression.Lambda(member, parameter); var call = Expression.Call( typeof(Enumerable), "Sum", new[] { type }, source, lambda); sum[property.Name + "Sum"] = new List().AsQueryable().Provider.Execute(call); } return sum; } } }