I have LINQ query that I want to generate dynamically:
var groupData =
from l in data
group l by l.Field1 into field1Group
select new MenuItem()
{
Key = field1Group.Key,
Count = field1Group.Count(),
Items = (from k in field1Group
group k by k.Field2 into field2Group
select new MenuItem()
{
Key = field2Group.Key,
Count = field2Group.Count()
}).ToList()
};
The ultimate goal is to be able to dynamically group the data by any combination of fields with no limit on the nested queries.
I can get as far as the first level but I'm struggling with the nested sub queries:
string field1 = "Field1";
string field2 = "Field2";
var groupDataD =
data.
GroupBy(field1, "it").
Select("new ( it.Key, it.Count() as Count )");
Is this possible with chained dynamic LINQ? Or is there a better way to achieve this?
The following should work (though personally I would rather avoid using such code):
Follow this answer to add the following in
ParseAggregate
, :Add
Select
,GroupBy
,ToList
intoIEnumerableSignatures
, and respective conditions inParseAggregate
, as explained in this answer:Finally, Your query would be:
Note that
"it"
holds a different instance when used in the parent query vs. the subquery. I tried to take advantage of"outerIt"
to overcome this conflation, but unfortunately without success (but maybe you'd succeed? maybe 1, 2 would help)A simple example for future reference: