C# 动态 LINQ:在字典索引器上使用 Sum 进行选择

sea*_*net 5 c# linq select dynamic-linq

我正在使用动态 LINQ 创建一个 groupby 并进行动态选择。我的项目是键/值集合(字典),因此它们不包含属性(这是设计要求,无法更改)。我能够解决另一个问题中的 groupby 部分,但它似乎在 select 方法中不起作用。

我的代码如下:

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

        // and now the select string
        StringBuilder selectSB = new StringBuilder();
        selectSB.Append("new ( ");
        useComma = false;
        foreach (var name in groupbyNames)
        {
            if (useComma)
                selectSB.Append(", ");
            else
                useComma = true;

            selectSB.Append("Key.")
                //.Append(name)
                //.Append(" as ")
                .Append(name);
        }
        foreach (var name in summableNames)
        {
            if (useComma)
                selectSB.Append(", ");
            else
                useComma = true;

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

        var groupby = list.GroupBy(groupBySB.ToString(), "it");
        var select = groupby.Select(selectSB.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

选择字符串的 Key 部分正常,但 Sum 部分不起作用。假设我想要的键称为值,我尝试过:

  • “Sum(value)”:ParseException:预期表达式

  • “Sum(\”value\”)”:ParseException:预期表达式

  • “Sum(it[\"value\"])”:ParseException:不存在适用的聚合方法“Sum”

  • “Sum(it[value])”:ParseException:“字典”类型中不存在属性或字段“值”

  • “Sum([\"value\"])”:ParseException:预期表达式

但一切都失败了。有任何想法吗?

谢谢!肖恩

Ada*_*lls 0

您的语法正确(我的测试字段是“一”和“二”)

new ( Key.One, Sum(it["Two"]) as Two )
Run Code Online (Sandbox Code Playgroud)

但是,没有 linq 方法 Sum(object),您需要告诉它它是什么求和(int、float、decimal 等)

最简单的方法是将字典定义更改为 Dictionary<'string, int> 假设您正在对整数求和。