如何通过组动态地构建一个字典名单 [英] How to build group-by dynamically on a list of dictionaries

查看:135
本文介绍了如何通过组动态地构建一个字典名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上一个IEnumerable执行GROUPBY。问题是,我不知道在编译时的字段我想GROUPBY。我发现堆栈上的另一个帖子说明如何做到这一点的时候类是已知并具有属性,但在我的情况我处理的字典和按键也只在运行时称。

I am trying to perform a groupby on an IEnumerable. The problem is that I do not know at compile-time which fields i want to groupby. I have found another post on stack that explains how to do this when the class is known and has properties, but in my case i am dealing with a dictionary and the keys are also only known at run-time.

我的代码将类似于这样的事情(我知道这不会编译...):

My code would resemble something like this (i know this doesn't compile...):

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,但我卡住了(因为我没有使用属性,但一个键/值集合)...

Any ideas? I've started looking into Dynamic LINQ but am stuck (because I am not using properties but a Key/Value collection)...

谢谢大家!

肖恩

推荐答案

所以我能够得到GROUPBY工作.. (select语句是另外一个问题)。感谢c0d1ng为把我在正确的道路上。语法不那么微不足道,因为我使用的索引,而不是性质...

So I am able to get the groupby to work... (the select statement is another question). Thanks to c0d1ng for putting me on the right path. The syntax was not so trivial because I am using indexers and not properties...

下面是我的代码:

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

这篇关于如何通过组动态地构建一个字典名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆