c# - 如何在字典列表上动态构建分组依据

标签 c# linq dynamic datatable group-by

我正在尝试对 IEnumerable 执行 groupby。问题是我在编译时不知道我想要对哪些字段进行分组。我找到了another post在堆栈上解释了当类已知并具有属性时如何执行此操作,但就我而言,我正在处理字典,并且键也仅在运行时已知。

我的代码类似于这样(我知道这不能编译...):

private object GetValuesGroupedBy(List<string> groupbyNames, List<string> summableNames)
{
     // get the list of items in the grid
     var listOfDicos = grid.AllItems;

     return listOfDicos
                .GroupBy(x => new { x[groupbyNames[0]], 
                                    x[groupbyNames[1]], 
                                    x[groupbyNames[2]] })
                .Select(group => new { group.Key, 
                                       group.Sum(x => x[summableNames[0]]), 
                                       group.Sum(x => x[summableNames[1]]) });
}  

有什么想法吗?我已经开始研究动态 LINQ 但陷入困境(因为我没有使用属性,而是使用键/值集合)...

谢谢大家!!

肖恩

最佳答案

所以我能够让 groupby 工作......(选择语句是另一个问题)。感谢 c0d1ng 让我走上了正确的道路。语法并不是那么简单,因为我使用的是索引器而不是属性......

下面是我的代码:

    private void GetValuesGroupedBy(List<Dictionary<string, object>> list, List<string> groupbyNames, List<string> summableNames)
    {
        // build the groupby string
        StringBuilder groupBySB = new StringBuilder();
        groupBySB.Append("new ( ");
        bool useComma = false;
        foreach (var name in groupbyNames)
        {
            if (useComma)
                groupBySB.Append(", ");
            else
                useComma = true;

            groupBySB.Append("it[\"");
            groupBySB.Append(name);
            groupBySB.Append("\"]");
            groupBySB.Append(" as ");
            groupBySB.Append(name);
        }
        groupBySB.Append(" )");

        var groupby = list.GroupBy(groupBySB.ToString(), "it");
    }

关于c# - 如何在字典列表上动态构建分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797997/

相关文章:

c# - LINQ to Dynamics CRM 在本地查询过滤记录

javascript - onchange 函数动态更新的问题

c# - 在完成线程之前等待 FileSystemWatcher 事件触发

c# - 将 js 值作为参数发送给 js 函数

c# - 子级不继承依赖属性值并采用默认值

c# - 删除 Entity Framework Core 查询中重复的 SUM 子查询

c# - Azure Web 作业失败 - ReadLine() 留在

c# - 如何使用 LINQ 获取 int 数组中的前 3 个元素?

Java常量通过构建字符串进行实例化

c# - 动态关键字、C# 和 Interop?