user2969983
user2969983

Reputation: 1

Linq multi level grouping

I am trying to implement a multi level grouping in linq

In sql it would be something like that.

Select VarId, variable, UT , 
       (case when resultat >= 0 then sum(resultat) else 0) as Positive,
       (case when resultat < 0 then sum(resultat) else 0) as Negatif
from 
      (Select VarId, variable, UT , valeur, sum( resultat ) from IndicRow 
             group by VarId, variable, UT , valeur)
group by VarId, variable, UT 

i have created that in linq but i can't find the way to group on the result of a group by

var Chartline = from IndicRow in Indic_dt.AsEnumerable()
                            //where SelTradeId.Contains(IndicRow.Field<int>("TradeNum"))
                            group IndicRow by new
                            {
                                GpVariable = IndicRow.Field<string>("Variable"),
                                GpUT = IndicRow.Field<string>("UT"),
                                GPVarId = IndicRow.Field<int>("VarId"),
                                GPValue = IndicRow.Field<double>("Valeur")
                            } into RdVal
                            select new
                            {
                                VarId = RdVal.Key.GPVarId,
                                Variable = RdVal.Key.GpVariable,
                                UT = RdVal.Key.GpUT,
                                Valeur = RdVal.Key.GPValue,
                                Resultat = RdVal.Sum(IndicRow => IndicRow.Field<double>("Resultat_EuroNet"))
                            };

The final goal is to obtain a 5 columns Datatable (VarId, variable, UT, Positive, negative)

Upvotes: 0

Views: 1344

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109118

The general pattern fro a two-level grouping is

from t in Mains
group t by t.GroupProperty1 into mainGroup
select new { mainGroup.Key,
             MainCount = mainGroup.Count(), 
             subGroups = from mg in mainGroup
                         group mg by mg.GroupProperty2 into subGroup
                         select new { subGroup.Key,
                                      SubCount = subGroup.Count()
                                    }
           }

So the main grouping is by VarId, variable, UT and the sub grouping only by valeur, because the sub group only contains items of one main group.

Upvotes: 1

Related Questions