c# - 使用 join、group-by 和 where 将 sql 转换为 linq

标签 c# linq join group-by aggregate

我有下面的sql,我想把它转换成linq

SELECT Contrato.finca, SUM(Pago.Importe_subtotal)
FROM Pago, Contrato
WHERE Pago.Contrato = Contrato.ID AND Pago.pagado = 1
GROUP BY Contrato.finca
ORDER BY 2 DESC
GO

我现在在 linq 中的内容如下,但是 group by 不起作用。

var x = from contrato in ctx.Contratos 
        join pago in ctx.Pagos
        on contrato.ID equals pago.Contrato 
        where pago.pagado == true 
        group contrato by contrato.finca
        select contrato.Finca1;

最佳答案

认为这应该可行:

ctx.Pagos.Where(m=>m.pagado==true).GroupBy(m=>m.Contrato.finca) 
    .Select(m=> new { Id= m.Key, Val= m.Sum(n => n.Importe_subtotal)})

关于c# - 使用 join、group-by 和 where 将 sql 转换为 linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14128357/

相关文章:

c# - Win8 ComboBox IsDropDownOpen + 可见性导致 UI 出现故障

VB.NET LINQ 查询 : Getting The Sum of All Values For A Specific Structure Member

c# - 在 Linq where 子句中使用带有字符串的 switch-case

c# - Linq - 检查所有但仅当至少有一个时

c# - 使用 WCF 实现观察者模式

c# - 如何连接控制台应用程序和 Windows 窗体应用程序 C#

c# - 在 Visual Studio 中使用 SQL Server 存储过程

mysql 查询以获得帖子 ID,例如 twitter homefeed,它将显示我们的帖子以及我们的关注帖子

php - 我想查询连接的记录(左连接)并将它们放入 PhP 中的数组结构中,如何?

MySQL 将子评论分组到父评论下未返回正确的数据结果