2011-04-13 57 views
4

我有多個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,但這是靜態的)。

感謝任何見解...

回答

8

如果有人很好奇,我得到了它的使用條件語句工作...因爲由空分組會使其崩潰。

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