4

動的 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());
    }

選択文字列のキー部分は問題ありませんが、合計部分は機能しません。必要なキーが値と呼ばれると仮定して、試しました:

  • "Sum(value)": ParseException: 式が必要です

  • "Sum(\"value\")": ParseException: 式が必要です

  • "Sum(it[\"value\"])": ParseException: 適用可能な集計メソッド「Sum」が存在しません

  • "Sum(it[value])": ParseException: タイプ 'Dictionary' にプロパティまたはフィールド 'value' が存在しません

  • "Sum([\"value\"])": ParseException: 式が必要です

しかし、すべて失敗しました。何か案は?

ありがとう!ショーン

4

2 に答える 2

0

あなたは正しい構文を持っています(私のテストフィールドは「One」と「Two」です)

new ( Key.One, Sum(it["Two"]) as Two )

ただし、linq メソッド Sum(object) はありません。Summing (int、float、decimal など) を指定する必要があります。

最も簡単な方法は、整数を合計していると仮定して、辞書の定義を Dictionary<'string, int> に変更することです。

于 2012-06-29T13:12:59.867 に答える