I have a situation where i have to calculate percentage of two values for example
IEnumerable result =
from r in renewalLists
gro
If you're wanting to pull values from the original query, and then populate an additional property, you can do it like this:
IEnumerable 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
});
Seems like you're doing an lot of "requerying" the same record in the individual assignments, though. You could probably accomplish the same thing in a much cleaner way by using a "join" on CityID.
Remember, that LINQ also supports subqueries:
IEnumerable result =
(from g in (
from r in renewalList
join c in cityList on r.CityID equals c.CityID
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()
})
group g by g.CityID into grpCity
select new RenewalModel
{
desiredCalucation = (g.PotentialRenewalCount / g.PotentialRenewalCount) * 100,
CityID = g.CityID,
City = g.City.Trim(),
PotentialRenewalCount = g.PotentialRenewalCount.Sum(),
PotentialRenewalSQRT = g.PotentialRenewalSQRT.Sum(),
RENEWALCOUNT = g.RENEWALCOUNT.Sum(),
RENEWALSQRT = g.RENEWALSQRT.Sum()
});