Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform calculation inside select statement in LINQ

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

IEnumerable<RenewalModel> result = 
    from r in renewalLists
    group r by r.CityID into grpCity
    select new RenewalModel
    {
        CityID = grpCity.Key,
        City = (from g in grpCity where g.CityID == grpCity.Key select g.City).First().Trim(),
        PotentialRenewalCount = (from g in grpCity where g.CityID == grpCity.Key select g.PotentialRenewalCount).Sum(),
        PotentialRenewalSQRT = (from g in grpCity where g.CityID == grpCity.Key select g.PotentialRenewalSQRT).Sum(),
        desiredCalucation=   (PotentialRenewalCount/PotentialRenewalCount)*100,
        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 my calculation should be like this

(PotentialRenewalCount/PotentialRenewalCount)*100

as i have described it inside the select statement.

i even tried this query but i get the 0 as result

 IEnumerable<RenewalModel> result =
            (from r in renewalLists
            group r by r.CityID into grpCity
            select new RenewalModel
            {
                CityID = grpCity.Key,
                City = (from g in grpCity where g.CityID == grpCity.Key select g.City).First().Trim(),
                PotentialRenewalCount = (from g in grpCity where g.CityID == grpCity.Key select g.PotentialRenewalCount).Sum(),
                PotentialRenewalSQRT = (from g in grpCity where g.CityID == grpCity.Key select g.PotentialRenewalSQRT).Sum(),
                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()
            }).select(r => new RenewalModel
            {
                desiredCalucation = (r.PotentialRenewalCount / r.PotentialRenewalCount) * 100,
                CityID = r.CityID,
                City = r.City,
                PotentialRenewalCount = r.PotentialRenewalCount,
                PotentialRenewalSQRT = r.PotentialRenewalSQRT,
                RENEWALCOUNT = r.RENEWALCOUNT,
                RENEWALSQRT = r.RENEWALSQRT
            });

for some reason or another desiredCalucation variable is giving me 0 as result.

any help is appreciated. Thank you

like image 710
Lijin Durairaj Avatar asked Jan 27 '26 07:01

Lijin Durairaj


1 Answers

For this purpose, use the LINQ let operator.

In general, I would recommend to split your big LINQ statement on several smaller ones. Otherwise, it will be very painful to debug this later.

like image 92
Ivan Yurchenko Avatar answered Jan 28 '26 20:01

Ivan Yurchenko