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}");
}
}