我正在尝试对 IEnumerable 执行 groupby 。问题是我在编译时不知道我想要对哪些字段进行分组。我已经发现另一个帖子在堆栈上解释了当类已知并且具有属性时如何执行此操作,但就我而言,我正在处理字典,并且键也仅在运行时已知。
我的代码类似于这样(我知道这不能编译......):
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 但陷入困境(因为我没有使用属性,而是使用键/值集合)...
谢谢大家!!
Sean
所以我能够让 groupby 工作...( select 语句是另一个问题)。感谢 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");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)