动态LINQ组按条款

问题描述:

我有多个LINQ查询,只是在不同的分组级别检索相同的数据。 (可能有3个不同的级别)。 linq查询当前会生成一个自定义对象的可枚举列表。我不明白或不知道如何可能的项目(以减少冗余代码):动态LINQ组按条款

我可以使以下group by子句是动态的吗? 如果是这样,它可以动态地填充我的自定义对象组数据,当它被分组在该级别。

例如:

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) 
       }; 

如果我想组只由“组名”,而不是...我会重写查询。我看到的问题是,如果我按值分组,那么我需要查询中的值(g.Key.GroupName);但由于我创建了一个新的自定义对象,其他非分组值(如“ClassName”)需要一个值(我在上面使用了string.Empty,但这是静态的)。

感谢任何见解...

如果有人很好奇,我得到了它的使用条件语句工作...因为由空分组会使其崩溃。

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

谢谢你的跟进。 – SixOThree 2011-12-02 19:20:15