gpt4 book ai didi

c# - IEnumerable Group 按用户指定的动态键列表

转载 作者:可可西里 更新时间:2023-11-01 08:48:47 26 4
gpt4 key购买 nike

我有一个类

public class Empolyee
{
public string Designation {get ;set;}
public string Discipline {get ;set;}
public int Scale {get ;set;}
public DateTime DOB {get ;set;}
public int Sales {get ;set;}
}

并以可枚举的方式记录所有员工

List<Employee> Employees;

和一个字符串键列表,例如

var Keys = new List<string>()
{
"Designation",
"Scale",
"DOB"
};

假设列表“键”的元素是用户指定的,用户可以不指定或指定多个键元素。

现在我想使用列表“Keys”中指定的键对所有“Employees”进行分组,并仅选择“Keys”中指定的属性以及每个组的销售额总和。

在我尝试使用的 3 个解决方案中,以下看起来适用但无法使用它,因为不知道列表“键”将如何转换为匿名类型

Employees.GroupBy(e => new { e.Key1, e.Key2, ... })
.Select(group => new {
Key1 = group.Key.Key1,
Key2 = group.Key.Key2,
...
TotalSales = group.Select(employee => employee.Sales).Sum()
});

最佳答案

您可能需要像 Dynamic LINQ 这样的东西因此您可以将键和投影值指定为字符串。

查看一些分组和投影示例:

关于c# - IEnumerable Group 按用户指定的动态键列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29915116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com