简体   繁体   English

动态linq group by子句

[英]dynamic linq group by clause

I have multiple linq queries that retrieve the same data just at different grouping levels. 我有多个linq查询,只在不同的分组级别检索相同的数据。 (potentially 3 different levels). (可能有3个不同的级别)。 The linq query currently results in an enumerable list of a custom object. linq查询当前导致自定义对象的可枚举列表。 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? 我可以将以下group by子句动态化吗? 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. 如果我只想通过“GroupName”进行分组......我会重写查询。 Issues I see are, if I'm grouping by a value then I need that value in the query (g.Key.GroupName); 我看到的问题是,如果我按值分组,那么我在查询中需要该值(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). 但由于我正在创建一个新的自定义对象,其他非分组值(如“ClassName”)需要一个值(我上面使用了string.Empty,但这是静态的)。

Thanks for any insight... 感谢您的任何见解......

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
                {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM