Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic linq group by clause

Tags:

c#

linq

I have multiple linq queries that retrieve the same data just at different grouping levels. (potentially 3 different levels). The linq query currently results in an enumerable list of a custom object. The items I don't understand or wonder if possible (to reduce redundant code):

can I make the following group by clause to be dynamic? if so, can it dynamically populate my custom object group data 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 => x.r.TPA / x.pc.Count),
                    TPADEV = g.Select(x => x.r.TPA).StdDev(g.Key.Count)
                };

If I wanted to group only by "GroupName" instead... I would rewrite the query. Issues I see are, if I'm grouping by a value then I need that value in the query (g.Key.GroupName); but since I'm creating a new custom object the other non-grouped values such as "ClassName" require a value (I used string.Empty above, but that is static).

Thanks for any insight...

like image 292
Tom Bass Avatar asked Feb 25 '23 12:02

Tom Bass


1 Answers

if anyone was curious, I got it to work by using a conditional statement... since grouping by empty will make it 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
                {}
like image 116
Tom Bass Avatar answered Mar 11 '23 20:03

Tom Bass