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

如何实现类SQL LIKE%的通配符搜索?当前仅支持包含匹配

实现类SQL LIKE通配符的LINQ模糊搜索

你当前的代码用Contains等价于SQL的LIKE '%xxx%',如果要实现更贴近SQL LIKE的通配符效果(前缀匹配LIKE 'xxx%'、后缀匹配LIKE '%xxx',甚至支持用户输入%作为通配符),可以按以下方式修改:

1. 固定场景的匹配实现

前缀匹配(对应LIKE '搜索词%')

使用StartsWith替代Contains,匹配以搜索词开头的记录:

var searchKeyUpper = searchKey.ToUpper();
List = (from x in employee 
        where x.firstname.ToUpper().StartsWith(searchKeyUpper) 
        || x.fullname.ToUpper().StartsWith(searchKeyUpper)  
        select x)
        .Take(5);

后缀匹配(对应LIKE '%搜索词')

使用EndsWith替代Contains,匹配以搜索词结尾的记录:

var searchKeyUpper = searchKey.ToUpper();
List = (from x in employee 
        where x.firstname.ToUpper().EndsWith(searchKeyUpper) 
        || x.fullname.ToUpper().EndsWith(searchKeyUpper)  
        select x)
        .Take(5);

2. 支持自定义通配符的灵活实现

如果要让用户能像写SQL一样,在搜索词里用%作为通配符(比如Joh%匹配前缀、%mith匹配后缀、%ohn%匹配包含),可以添加通配符解析逻辑:

var searchKeyUpper = searchKey.ToUpper().Trim();
var hasLeadingWildcard = searchKeyUpper.StartsWith("%");
var hasTrailingWildcard = searchKeyUpper.EndsWith("%");
var actualMatchKey = searchKeyUpper.Trim('%');

List = (from x in employee
        where 
            // 根据通配符位置选择匹配逻辑
            (hasLeadingWildcard && hasTrailingWildcard 
                ? x.firstname.ToUpper().Contains(actualMatchKey) || x.fullname.ToUpper().Contains(actualMatchKey)
                : hasLeadingWildcard
                    ? x.firstname.ToUpper().EndsWith(actualMatchKey) || x.fullname.ToUpper().EndsWith(actualMatchKey)
                    : hasTrailingWildcard
                        ? x.firstname.ToUpper().StartsWith(actualMatchKey) || x.fullname.ToUpper().StartsWith(actualMatchKey)
                        // 无通配符时默认前缀匹配,可根据需求调整为全匹配
                        : x.firstname.ToUpper().StartsWith(actualMatchKey) || x.fullname.ToUpper().StartsWith(actualMatchKey))
        select x)
        .Take(5);

额外优化提示

如果使用EF Core等ORM框架,StartsWith/EndsWith/Contains会被直接转译为SQL的LIKE语句,避免在客户端过滤数据,性能更优。此外,也可以用StringComparison.OrdinalIgnoreCase代替ToUpper(),减少大小写转换的开销:

x.firstname.StartsWith(searchKey, StringComparison.OrdinalIgnoreCase)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:20:26