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

如何在对象列表中递归搜索指定字符串关键词

通用对象列表关键词搜索实现

我最近搞定了一个通用的搜索功能,能在任意类型的对象列表里筛选出包含指定关键词的对象——只要关键词出现在对象的任意字符串属性中就行。下面是完整的实现代码和细节说明:

IEnumerable 扩展方法(集合搜索入口)

这个扩展方法给所有可枚举集合添加了Search能力,会自动调用对象的Contains方法判断是否匹配:

public static class IEnumerableExtensions
{
    public static IEnumerable<T> Search<T>(this IEnumerable<T> items, string search)
    {
        if (!string.IsNullOrEmpty(search))
            items = items.Where(i => i.Contains(search));
        return items;
    }
}

Object 扩展方法(对象匹配逻辑)

这部分是核心的匹配逻辑,通过反射遍历对象的所有字符串属性,检查是否包含搜索关键词:

public static class ObjectExtensions
{
    public static bool Contains<T>(this T obj, string searchTerm)
    {
        if (obj == null) return false;
        
        // 获取对象所有可读的字符串类型属性
        var stringProperties = typeof(T).GetProperties()
            .Where(prop => prop.PropertyType == typeof(string) && prop.CanRead);
        
        foreach (var prop in stringProperties)
        {
            var propValue = prop.GetValue(obj) as string;
            // 忽略空值,不区分大小写检查是否包含关键词
            if (!string.IsNullOrEmpty(propValue) && propValue.Contains(searchTerm, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
        }
        
        return false;
    }
}

额外说明

  • 我在Contains方法里加了StringComparison.OrdinalIgnoreCase,实现不区分大小写的搜索,如果需要区分大小写,改成StringComparison.Ordinal就行
  • 特意处理了对象为null的情况,避免空引用异常
  • 当搜索关键词为空或null时,Search方法会直接返回原集合,符合空搜索返回全部内容的常见需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:12:10