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

如何在LINQ的WHERE子句中添加条件:仅Maths科目需Score>50

LINQ查询条件调整方案

问题背景

数据表结构

字段:Id, Name, Subject, Score

原始数据

1 Pinky English 60
2 Pinky Maths 40
3 Mahesh Maths 50
4 Rani  Maths 50
5 Rani  Eco 50

查询需求

当Subject为Maths时,仅保留Score≥50的记录;其他科目无额外筛选条件。

期望输出

1 Pinky English 60
3 Mahesh Maths 50
4 Rani  Maths 50
5 Rani  Eco 50

当前已有LINQ查询

(from tbl in dbContext.Table1
where tbl.Subject = 'Maths' // 注:此处存在语法错误,C#判断相等需用==而非=
select tbl)

修正后的查询方案

你需要调整WHERE子句的逻辑,通过**逻辑或(||)**覆盖两种合法场景:

  1. 科目不是Maths,直接保留;
  2. 科目是Maths,同时满足Score≥50。

写法一(直观版)

(from tbl in dbContext.Table1
where tbl.Subject != "Maths" || (tbl.Subject == "Maths" && tbl.Score >= 50)
select tbl)

写法二(反向排除版)

也可以用反向逻辑,排除掉所有Subject为Maths且Score<50的记录,结果完全一致:

(from tbl in dbContext.Table1
where !(tbl.Subject == "Maths" && tbl.Score < 50)
select tbl)

额外说明

原查询中的tbl.Subject = 'Maths'是语法错误,C#中判断相等需要用==而非赋值符号=,修正后的代码已修复该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:54:52