You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含子查询、分组及Having子句的SQL转换为LINQ?

对应的LINQ实现

下面提供两种常见的LINQ写法,完全匹配你给出的SQL逻辑:

1. 查询语法(结构贴近SQL,易读性强)

// 先获取符合条件的发票号集合(对应SQL子查询)
var targetInvoices = from p in payments
                     where p.Invoice.StartsWith("EVENT") && p.Status == 3 && p.Date >= new DateTime(2023, 11, 1)
                     group p by p.Invoice into grouped
                     where grouped.Count() > 1
                     select grouped.Key;

// 筛选目标发票号的支付记录并排序
var result = from p in payments
             where targetInvoices.Contains(p.Invoice)
             orderby p.Invoice, p.Date descending
             select new {
                 p.Invoice,
                 p.Date,
                 p.Amount,
                 p.Name
             };

2. 方法链语法(代码更紧凑)

// 获取符合条件的发票号集合
var targetInvoices = payments
    .Where(p => p.Invoice.StartsWith("EVENT") && p.Status == 3 && p.Date >= new DateTime(2023, 11, 1))
    .GroupBy(p => p.Invoice)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key);

// 查询并排序结果
var result = payments
    .Where(p => targetInvoices.Contains(p.Invoice))
    .OrderBy(p => p.Invoice)
    .ThenByDescending(p => p.Date)
    .Select(p => new {
        p.Invoice,
        p.Date,
        p.Amount,
        p.Name
    });

关键对应说明

  • StartsWith("EVENT") 等价于SQL的 invoice like 'EVENT%'
  • 分组后通过Count() > 1实现having count(*) > 1的逻辑
  • Contains方法对应SQL的in子查询
  • OrderBy+ThenByDescending实现多字段排序要求

内容的提问来源于stack exchange,提问作者CaptainMorgan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 09:37:05