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

C#技术问询:如何从字符串列表中筛选包含字符串数组元素的项

解决方法:从列表中筛选包含指定关键词的项

嗨,这个需求其实很好实现,我给你分享几种实用的方案,你可以根据自己的场景选择:

1. 用LINQ快速实现(最推荐)

LINQ的组合写法非常简洁,一行核心代码就能搞定筛选逻辑:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] stringArray = {"car", "bike", "truck"};
        List<string> stringList = new List<string>{"car_blue", "car_red", "truck_yellow", "ship_black", "rocket_orange"};
        
        // 筛选包含任意关键词的项
        var filteredItems = stringList
            .Where(item => stringArray.Any(keyword => item.Contains(keyword)))
            .ToList();
        
        // 打印验证结果
        foreach (var item in filteredItems)
        {
            Console.WriteLine(item);
        }
    }
}

补充:精准匹配前缀的场景

如果你的需求是关键词必须出现在字符串开头(比如示例里的car_blue是car开头),可以把Contains换成StartsWith,这样能避免误匹配(比如如果有个blue_car就不会被选中):

var filteredItems = stringList
    .Where(item => stringArray.Any(keyword => item.StartsWith(keyword)))
    .ToList();

2. 不用LINQ的循环写法(适合新手理解)

如果你不想用LINQ,嵌套循环的写法逻辑更直观,容易上手:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string[] stringArray = {"car", "bike", "truck"};
        List<string> stringList = new List<string>{"car_blue", "car_red", "truck_yellow", "ship_black", "rocket_orange"};
        
        List<string> filteredItems = new List<string>();
        
        foreach (var item in stringList)
        {
            foreach (var keyword in stringArray)
            {
                if (item.Contains(keyword)) // 同样可以换成StartsWith
                {
                    filteredItems.Add(item);
                    break; // 找到匹配就跳出内层循环,提升效率
                }
            }
        }
        
        // 打印验证结果
        foreach (var item in filteredItems)
        {
            Console.WriteLine(item);
        }
    }
}

3. 大数据量优化:用HashSet提升效率

如果你的stringArray关键词数量多,或者stringList的数据量很大,建议把关键词数组转成HashSet<string>,这样查找的效率会显著提升:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] stringArray = {"car", "bike", "truck"};
        List<string> stringList = new List<string>{"car_blue", "car_red", "truck_yellow", "ship_black", "rocket_orange"};
        
        var keywordSet = new HashSet<string>(stringArray);
        var filteredItems = stringList
            .Where(item => keywordSet.Any(keyword => item.Contains(keyword)))
            .ToList();
        
        foreach (var item in filteredItems)
        {
            Console.WriteLine(item);
        }
    }
}

以上几种方法运行后,都会输出你预期的结果:car_blue、car_red和truck_yellow。

内容的提问来源于stack exchange,提问作者Little Flying Turtle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:00:36