我正在使用动态 LINQ 创建一个 groupby 并即时选择。我的项目是键/值集合(字典),因此它们不包含任何属性(这是设计要求,无法更改)。我能够解决 another question 中的 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());
}
选择字符串的 Key 部分可以,但 Sum 部分不起作用。假设我想要的键称为值,我试过:
“总和(值)”:ParseException:预期表达式
"Sum(\"value\")": ParseException: 表达式预期
"Sum(it[\"value\"])": ParseException: 不存在适用的聚合方法“Sum”
“Sum(it[value])”:ParseException:类型“Dictionary”中不存在属性或字段“value”
"Sum([\"value\"])": ParseException: 预期表达式
但都失败了。有什么想法吗?
谢谢! 肖恩
最佳答案
我自己也遇到过这个问题;问题是 Sum()
将列视为 object
类型(可应用于 Convert()
或 Max ()
偶数,但不是 Sum()
),因此失败;请注意,它表示没有适用聚合函数。
解决方案是使用到整数的内联转换。动态 LINQ 支持这种转换,并且可以在您的示例中按如下方式完成:
selectSB.Append("Sum(")
.Append("Convert.ToInt32(") // Add this...
.Append("it[\"")
.Append(name)
.Append("\"]")
.Append(")") // ... and this
.Append(") as ")
.Append(name);
如果您的列不是 int
类型,我相信 ToInt64
(bigint
) 和 ToDouble() 一样有效
和 ToDecimal()
。
关于C# 动态 LINQ : Select with Sum on dictionary indexer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10816700/