Mark
Mark

Reputation: 7818

Calculate a percentage column in controller for use in view

Is it possible to calculate in the controller, a percentage column which takes the sum of another number in the model, as its denominator - so something like:

 var sites = db.Calls.Where(x =>x.status != "Resolved" && x.status != "Closed").GroupBy(calls => new { calls.site })
          .Select(s => new SiteVM
          {
              Site = s.Key.site,
              Number = s.Count(),
              Perc = s.Count() / s.Sum(x => x.site.Count())
          }).OrderByDescending(z => z.Number);

I know this part isn't right: s.Sum(x => x.site.Count())

So Perc should be the number divided by the sum of the s.Count, for example:

Site        Number    Perc (number / sum of number)
London      100       50
Birmingham  30        15
Glasgow     70        35

Thank you,

Mark

Upvotes: 0

Views: 865

Answers (1)

Egor4eg
Egor4eg

Reputation: 2708

You can do this:

var calls = db.Calls.Where(x =>x.status != "Resolved" && x.status != "Closed").ToList();
var callsCount = calls.Count();

var sites = calls.GroupBy(calls => new { calls.site })
          .Select(s => new SiteVM
          {
              Site = s.Key.site,
              Number = s.Count(),
              Perc = callsCount / s.Count() * 100
          }).OrderByDescending(z => z.Number);

Upvotes: 1

Related Questions