一个通用的 C# 类 SumHelper
,用于计算集合中各个属性的合计。这个方法CalculateSums<T>
使用 LINQ 和表达式树来动态计算属性的总和.
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace YourNamespace
{
/// <summary>
/// 合计帮助类
/// </summary>
public static class SumHelper
{
/// <summary>
/// 属性合计
/// </summary>
public static Dictionary<string, decimal> CalculateSums<T>(IEnumerable<T> list) where T : class
{
var type = typeof(T);
var sum = new Dictionary<string, decimal>();
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), "x");
var member = Expression.Property(parameter, property);
// 处理可空类型
var convertedMember = Expression.Convert(member, typeof(decimal));
// 创建 lambda 表达式
var lambda = Expression.Lambda<Func<T, decimal>>(convertedMember, parameter);
// 计算总和
var sumValue = list.AsQueryable().Sum(lambda);
sum[property.Name + "Sum"] = sumValue;
}
return sum;
}
}
}
public class SampleData
{
public int Value1 { get; set; }
public decimal Value2 { get; set; }
public double? Value3 { get; set; }
}
public class Program
{
public static void Main()
{
var dataList = new List<SampleData>
{
new SampleData { Value1 = 10, Value2 = 20.5m, Value3 = 1.5 },
new SampleData { Value1 = 5, Value2 = 10.5m, Value3 = null },
new SampleData { Value1 = 15, Value2 = 30.0m, Value3 = 2.5 }
};
var sums = SumHelper.CalculateSums(dataList);
foreach (var sum in sums)
{
Console.WriteLine($"{sum.Key}: {sum.Value}");
}
}
}