Perform calculation inside select statement in LINQ

前端 未结 5 870
攒了一身酷
攒了一身酷 2021-01-21 02:17

I have a situation where i have to calculate percentage of two values for example

IEnumerable result = 
    from r in renewalLists
    gro         


        
5条回答
  •  梦毁少年i
    2021-01-21 02:36

    Altough I do not understand why one would devide a number by itself just to multiply it by 100 - I believe the thing you're looking for is called let. Now, I have not tested this but it should work somehow similar to this:

    IEnumerable result = 
        from r in renewalLists
        group r by r.CityID into grpCity
        let potentialRenewalCount = (from g in grpCity where g.CityID == grpCity.Key select g.PotentialRenewalCount).Sum()
        let desiredCalculation = (PotentialRenewalCount/PotentialRenewalCount)*100
        select new RenewalModel
        {
        CityID = grpCity.Key,
        City = (from g in grpCity where g.CityID == grpCity.Key select g.City).First().Trim(),
        PotentialRenewalCount = potentialRenewalCount,
        PotentialRenewalSQRT = (from g in grpCity where g.CityID == grpCity.Key select g.PotentialRenewalSQRT).Sum(),
        DesiredCalucation =   desiredCalculation,
        RENEWALCOUNT = (from g in grpCity where g.CityID == grpCity.Key select g.RENEWALCOUNT).Sum(),
        RENEWALSQRT = (from g in grpCity where g.CityID == grpCity.Key select g.RENEWALSQRT).Sum()
    };
    

    And also think about the case when the SUM is 0 since this would lead to a division by zero!

提交回复
热议问题