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

标签 c# .net asp.net-mvc lambda ienumerable

我有一个类

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/

相关文章:

c# - .NET Core 中的 Nuget 依赖项

c# - Collection<T> 类及其用途

c# - 通过单击第 3 方 .NET 应用程序的按钮自动用户登录 PHP 网站

asp.net-mvc - 使用命令从 Resharper 5 Intellisense 切换到 Visual Studio Intellisense

c# - 带有 Entity Framework 的 MVC 中的列表框控件

c# - 如何打破 View Controller 和数据源之间的引用循环

c# - 从另一个对象中获取 SignalR Core 中的 Hub 上下文

c# - 使用简单注入(inject)器注册 IAuthenticationManager

Javascript 与 Selenium WebDriver : "Can' t find variable: $"

c# - 如何映射组件集合(值对象)