44 lines
1.7 KiB
C#
44 lines
1.7 KiB
C#
using System.Linq.Expressions;
|
|
using System.Reflection;
|
|
|
|
namespace YLErp.Helpers
|
|
{
|
|
/// <summary>
|
|
/// 合计帮助类
|
|
/// </summary>
|
|
public static class SumHelper
|
|
{
|
|
/// <summary>
|
|
/// 属性合计
|
|
/// </summary>
|
|
public static Dictionary<string, object> CalculateSums<T>(IEnumerable<T> list) where T : class
|
|
{
|
|
var type = typeof(T);
|
|
var sum = new Dictionary<string, object>();
|
|
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<T>));
|
|
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<int>().AsQueryable().Provider.Execute(call);
|
|
}
|
|
return sum;
|
|
}
|
|
}
|
|
}
|