如何在字典列表上动态构建分组

我试图在IEnumerable上执行groupby。 问题是我在编译时不知道我想要分组的字段。 我在堆栈上发现了另一个post ,解释了当类已知且具有属性时如何执行此操作,但在我的情况下,我正在处理字典,并且键也仅在运行时已知。

我的代码会像这样(我知道这不会编译……):

private object GetValuesGroupedBy(List groupbyNames, List 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但是卡住了(因为我没有使用属性而是键/值集合)…

谢谢大家!!

肖恩

这将对您有所帮助: http : //weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

而且: 动态LINQ OrderBy在IEnumerable

所以我能够让groupby工作……(select语句是另一个问题)。 感谢c0d1ng让我走上了正确的道路。 语法不是那么简单,因为我使用索引器而不是属性…

以下是我的代码:

  private void GetValuesGroupedBy(List> list, List groupbyNames, List 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"); }