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

C# EF中Linq的Where多AND条件查询如何自动跳过空搜索词

LINQ多可选搜索词AND匹配查询修正方案

问题原因

原查询的条件逻辑错误:当某个搜索词为空时,!string.IsNullOrEmpty(sx) && s.ToLower().Contains(sx) 整个子句返回false,AND逻辑下会直接判定整个匹配失败,导致符合其余非空搜索词的结果被过滤。

修正方案

把每个搜索词的判断逻辑调整为:如果搜索词为空则直接返回true(跳过该条件),否则执行包含匹配,逻辑为 string.IsNullOrEmpty(sx) || s.ToLower().Contains(sx.ToLower())
修正后的完整代码如下:

using System;
using System.Linq;
public class Simple {
  public static void Main() {
    string[] names = { "Burke laptop mobile", "laptop burke mobile", "Computer Laptop", 
                       "Mobile", "Ahemed", "Sania", 
                       "Kungada", "David","United","Sinshia" };

    //搜索词
    string s1 = "mobile";
    string s2 = "";
    string s3 = "laptop";
    
    var query = from s in names 
                where (string.IsNullOrEmpty(s1) || s.ToLower().Contains(s1.ToLower())) 
                      && (string.IsNullOrEmpty(s2) || s.ToLower().Contains(s2.ToLower()))
                      && (string.IsNullOrEmpty(s3) || s.ToLower().Contains(s3.ToLower()))
                orderby s
                select s.ToUpper();

    foreach (string item in query)
      Console.WriteLine(item);
  }
}

额外优化建议

  • 如果是EF Core场景使用该查询,上述写法可以被正确翻译为SQL语句,空搜索词对应的条件会被自动忽略,不会生成冗余的SQL判断
  • 如果后续需要扩展搜索词数量,建议先过滤所有非空搜索词再批量匹配,代码扩展性更强:
// 过滤所有非空搜索词并统一转小写
var validSearchWords = new[] {s1, s2, s3}
                        .Where(w => !string.IsNullOrEmpty(w))
                        .Select(w => w.ToLower())
                        .ToList();
var query = names.Where(s => validSearchWords.All(w => s.ToLower().Contains(w)))
                 .OrderBy(s => s)
                 .Select(s => s.ToUpper());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:57:03