score:0

You have the correct syntax (my test fields are "One" and "Two")

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

However there is no linq method Sum(object), you need to tell it what it is Summing (int, float, decimal etc)

The easiest way is to change the dictionary definition to Dictionary<'string, int> assuming you are summing integers.

score:2

I faced this issue myself; the problem is that Sum() is seeing the column as type object (which can be applied to Convert(), or Max() even, but not Sum()), and thus is failing; note that it says there is no applicable aggregate function.

The solution is to use an inline conversion to integer. Dynamic LINQ supports this conversion, and can be done as follows in your example:

selectSB.Append("Sum(")
    .Append("Convert.ToInt32(") // Add this...
    .Append("it[\"")
    .Append(name)
    .Append("\"]")
    .Append(")") // ... and this
    .Append(") as ")
    .Append(name);

If your columns aren't int type, I believe ToInt64 (bigint) works, as well as ToDouble() and ToDecimal().


Related Articles