问题
I am trying to perform a groupby on an IEnumerable. The problem is that I do not know at compile-time which fields i want to groupby. I have found another post on stack that explains how to do this when the class is known and has properties, but in my case i am dealing with a dictionary and the keys are also only known at run-time.
My code would resemble something like this (i know this doesn't compile...):
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]]) });
}
Any ideas? I've started looking into Dynamic LINQ but am stuck (because I am not using properties but a Key/Value collection)...
Thanks everybody!!
Sean
回答1:
This will help you: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
And this: Dynamic LINQ OrderBy on IEnumerable<T>
回答2:
So I am able to get the groupby to work... (the select statement is another question). Thanks to c0d1ng for putting me on the right path. The syntax was not so trivial because I am using indexers and not properties...
Below is my code:
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");
}
来源:https://stackoverflow.com/questions/10797997/how-to-build-group-by-dynamically-on-a-list-of-dictionaries