Dynamic linq group by condition

I have several linq queries that retrieve the same data only at different levels of grouping. (potentially 3 different levels). The linq query currently leads to an enumerable list of a custom object. Elements that I do not understand or are not interested in, if possible (to reduce redundant code):

Can I make the following group by clause as dynamic? if so, can it dynamically populate my user data for a group of objects when it is grouped at that level.

For instance:

var myReport_GroupProductLevel = from r in mySum_GroupProductLevel join pc in _myPlotCount on r.Strata equals pc.Strata join acr in _myStrataAcres on pc.Strata equals acr.Strata group new { r, pc, acr } by new { r.Strata, pc.Count, acr.Acres, r.GroupName, r.ProductName } into g select new DataSummary { Strata = g.Key.Strata, PlotCount = g.Key.Count, Acres = g.Key.Acres, ClassName = string.Empty, GroupName = g.Key.GroupName, ProductName = g.Key.ProductName, TPAMEAN = g.Sum(x => xrTPA / x.pc.Count), TPADEV = g.Select(x => xrTPA).StdDev(g.Key.Count) }; 

If I wanted to group only "GroupName", then ... I would rewrite the request. The problems that I see are if I group the value, then I need this value in the request (g.Key.GroupName); but since I am creating a new custom object, other non-group values, such as "ClassName", require a value (I used string.Empty above, but it is static).

Thank you for understanding...

+4
source share
1 answer

if anyone was curious, I got it to work with a conditional statement ... since grouping empty will lead to its collapse.

 var mySum_ClassGroupProductLevel = from s in ReportData.myStands join p in ReportData.myPlots on s.ID equals p.StandID join t in ReportData.myTrees on p.ID equals t.PlotID group t by new { s.Strata, p.ID, ClassName = useClassName ? t.ClassName : string.Empty, GroupName = useGroupName ? t.GroupName : string.Empty, ProductName = useProductName ? t.ProductName : string.Empty } into g select new {} 
+8
source

Source: https://habr.com/ru/post/1347979/


All Articles