开发者

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
                  };


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜