c# - LINQ to SQL 连接和求和

标签 c# linq-to-sql

任何人都可以 LINQ 以下 SQL 吗?

我现在已经研究了两个小时,但与刚开始时相比,我并没有更接近于理解它。

SELECT ArticleId, sum(Amount) AS VoteCount
FROM  ArticleVotes INNER JOIN
Votes ON ArticleVotes.voteId = Votes.id
GROUP BY ArticleVotes.articleId
ORDER BY VoteCount DESC

表格如下;

ArticleVotes: ArticleId, VoteId

投票:id,数量

最佳答案

from articleVote in ArticleVotes
join vote in Votes on art.voteId equals vote.id
group articleVote by artarticleVote.articleId
select new 
{
ArticleId = art.ArticleID,
VoteCount = Votes.Sum(vote.amount)
}
orderby VoteCount

我不完全确定 orderby 部分,就此而言,我也不确定其余部分,因为我无法对其进行测试。如果它不起作用,请不要怪我:)

更新:使用 OP 的工作:

from artVotes in ArticleVotes
join vote in Votes on artVotes.VoteId equals vote.Id
group artVotes by artVotes.ArticleId into g
let totalAmount = g.Sum(p => p.Vote.Amount)
orderby totalAmount descending
select new { ArticleId = g.Key, total = totalAmount}

编辑 修复了 orderby 以使用降序。

感谢 op 让我有理由使用 let 运算符,并最终意识到它的美妙之处。仅仅通过提出问题,您就对我的问题提供了极大的帮助。为此 +1。

关于c# - LINQ to SQL 连接和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1285710/

相关文章:

sql - vb.net linq 插入新记录

c# - 使用 AES 在 C# 中加密文件,使用 phpseclib 解密

C# 将表达式作为参数传递并使用 PredicateBuilder

c#-4.0 - 使用 C# 代码将字节数组转换为 pdf

c# - WPF UI 允许用户构建复杂查询并输出表达式树

c# - 林奇 : Error using multiple from and Join

c# - 如何从 Linq 读取大型 XML RAW 到 SQL?

c# - 为什么在写入 StreamWriter 时会得到 System.Collections.Generic.Dictionary`2?

c# - 替换列中的多个字符串元素

c# - RGraph 和 IE 8 无法正确渲染图形