如何在字典列表上动态构建分组依据 [英] How to build group-by dynamically on a list of dictionaries

查看:26
本文介绍了如何在字典列表上动态构建分组依据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 IEnumerable 执行 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天全站免登陆