Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: sum all values and assign a percentage of the total in Linq to sql

I have a simple linq query that I'm trying to extend so that I can first sum all the values in the VoteCount field and then for each Nominee I want to assign what percentage of votes the nominee received.

Here's the code:

              TheVoteDataContext db = new TheVoteDataContext();
    var results = from n in db.Nominees
                  join v in db.Votes on n.VoteID equals v.VoteID
                  select new
                  {
                      Name = n.Name,
                      VoteCount = v.VoteCount,
                      NomineeID = n.NomineeID,
                      VoteID = v.VoteID
                  };
like image 745
Donnie Avatar asked Dec 13 '25 06:12

Donnie


1 Answers

Since selecting the single votes for each nominee and calculating the sum of all votes are two different tasks, I cannot think of a way of doing this efficiently in one single query. I would simply do it in two steps, as

var results = from n in db.Nominees
              join v in db.Votes on n.VoteID equals v.VoteID
              select new
              {
                  Name = n.Name,
                  VoteCount = v.VoteCount,
                  NomineeID = n.NomineeID,
                  VoteID = v.VoteID
              };

var sum = (decimal)results.Select(r=>r.VoteCount).Sum();
var resultsWithPercentage = results.Select(r=>new {
                               Name = r.Name,
                               VoteCount = r.VoteCount,
                               NomineeID = r.NomineeID,
                               VoteID = r.VoteID,
                               Percentage = sum != 0 ? (r.VoteCount / sum) * 100 : 0
                            });

You could also calculate the sum before the results (using an aggregate query), this would leave the task of summing to the Database engine. I believe that this would be slower, but you can always find out by trying :)

like image 124
MartinStettner Avatar answered Dec 14 '25 18:12

MartinStettner