我有一个简单的linq查询,我正在尝试扩展,以便我可以先在VoteCount字段中汇总所有值,然后为每个被提名者我想分配被提名者收到的投票百分比。
以下是代码:
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
};
答案 0 :(得分:7)
由于为每个被提名者选择单票并计算所有投票的总和是两个不同的任务,我无法想到在一个查询中有效执行此操作的方法。我只需要分两步完成,如
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
});
您还可以在结果之前计算总和(使用聚合查询),这会将求和任务留给数据库引擎。我相信这会慢一点,但你总能通过尝试找出答案:)