我正在尝试对 IEnumerable 执行 groupby。问题是我在编译时不知道我想要对哪些字段进行分组。我找到了another post在堆栈上解释了当类已知并具有属性时如何执行此操作,但就我而言,我正在处理字典,并且键也仅在运行时已知。
我的代码类似于这样(我知道这不能编译...):
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 但陷入困境(因为我没有使用属性,而是使用键/值集合)...
谢谢大家!!
肖恩
最佳答案
所以我能够让 groupby 工作......(选择语句是另一个问题)。感谢 c0d1ng 让我走上了正确的道路。语法并不是那么简单,因为我使用的是索引器而不是属性......
下面是我的代码:
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");
}
关于c# - 如何在字典列表上动态构建分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797997/