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

如何使用LINQ查询筛选以指定编码前缀开头的字符串列表条目

实现方案

你可以通过以下两种LINQ写法实现需求,可根据业务是否需要保留重复条目选择:

1. 与原foreach逻辑完全等效(单条匹配多前缀时会重复添加到结果)

原双重foreach逻辑下,如果一个条目同时匹配codes中的多个前缀,会被多次加入结果列表,对应LINQ实现如下:

private static List<string> GetValidList(List<string> inputValues, List<string> codes)
{
    return inputValues
        .SelectMany(item => codes.Where(code => item.StartsWith(code)).Select(_ => item))
        .ToList();
}

2. 常用去重版本(单条匹配多前缀时仅保留一次)

绝大多数筛选场景下不需要重复条目,可使用Where+Any的组合实现:

private static List<string> GetValidList(List<string> inputValues, List<string> codes)
{
    return inputValues
        .Where(item => codes.Any(code => item.StartsWith(code)))
        .ToList();
}

如果需要大小写不敏感的前缀匹配,可修改StartsWith参数为:
item.StartsWith(code, StringComparison.OrdinalIgnoreCase)


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:15:01