C# 构建具有多个字段的 GroupBy 表达式树

 

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;
}
View Code

 

 

 var people = new List<Person>
 {
     new() { Name = "Charlie", Age = 25, City = "Los Angeles" },
     new() { Name = "Alice", Age = 25, City = "New York" },
     new() { Name = "David", Age = 35, City = "Chicago" },
     new() { Name = "Bob", Age = 30, City = "New York" },
     new() { Name = "Eve", Age = 25, City = "New York" }
 };

 // 使用LINQ查询来应用动态排序  
 var orderByFields = new[] { "Name", "Age" }; // 要排序的字段名数组  
 var ascending = new[] { true, false }; // 每个字段的排序方向(升序/降序)数组  

 //多条件排序
 var sortedPeople = people.AsQueryable()
     .OrderByMultipleFields(orderByFields, ascending)
     .ToList();


 // 定义要根据哪些属性进行分组  
 string[] groupByProperties = { "Age", "City" };
 // 构建分组表达式  
 Expression<Func<Person, object>> groupByExpression = DynamicLinqExtensions.GroupByExpression<Person>(groupByProperties);
         
 // 执行分组和求和查询  
 var groups = people
     .GroupBy(groupByExpression.Compile()) // 使用编译后的lambda表达式进行分组  
     //.Select(group => new // 选择每个组的信息  
     //{
     //    Key = group.Key, // 组的键(即多条件组合)  
     //    TotalAmount = group.Sum(item => item.Age) // 组内Amount的和  
     //})
     .ToList(); // 将结果转换为List 

 foreach (var group in groups)
 {
     Console.WriteLine($"Group: {string.Join(", ", group.Key)}");
     foreach (var person in group)
     {
         Console.WriteLine($"  {person.Name}");
     }
 }
View Code

 

 

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

 

摘自与:c# - 构建具有多个字段的 GroupBy 表达式树 - IT工具网 (coder.work)

posted @ 2024-04-12 14:50  SmilePastaLi  阅读(142)  评论(0)    收藏  举报