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

C# Linq关联Customer与Payment表查询2021年无支付记录客户

原有代码的问题

  • 语法错误:join子句后应该使用in关键字而非from
  • 逻辑错误:直接关联后再筛选支付年份,会提前过滤掉本身没有任何支付记录的客户,且into分组后的计数调用写法也不正确,无法得到预期结果。

正确实现方式

方式1:查询语法(左连接实现)

using System.Linq;

var result = from customer in context.Customers
             // 先过滤出2021年的支付记录再做左连接
             join payment in context.Payments.Where(p => p.Year == 2021)
             on customer.CustomerId equals payment.CustomerId into customerPayments
             // 筛选没有匹配到2021年支付记录的客户
             where !customerPayments.Any()
             select customer;

方式2:方法语法(NOT EXISTS逻辑,更简洁高效)

using System.Linq;

var result = context.Customers
    .Where(c => !context.Payments.Any(p => 
        p.CustomerId == c.CustomerId 
        && p.Year == 2021))
    .ToList();

该写法最终生成的SQL是标准的NOT EXISTS查询,执行效率更高,逻辑也更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:39:02