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

C#中筛选List<List<string>>匹配子列表的优化方案咨询

优化List<List>的筛选与复制实现

问题描述

现有List<List<string>>类型集合Full,每个子列表的指定索引元素(示例中为索引1,对应string2)需要与List<string>集合Strings中的元素匹配。需创建新集合NewList,仅包含Full中满足“子列表指定索引元素存在于Strings”的子列表。

示例代码

List<List<string>> Full = new List<List<string>>()
{
    new List<string>() { "11", "AA", "!!", },
    new List<string>() { "22", "BB", "@@", },
    new List<string>() { "33", "CC", "##", },
    new List<string>() { "44", "DD", "$$", },
};

List<string> Strings = new List<string>()
{
    "AA", "DD",
};

期望NewList结果:

sublist0: "11", "AA", "!!"; //匹配"AA"
sublist1: "44", "DD", "$$"; //匹配"DD"

当前硬编码实现

List<List<string>> Full;
List<string> Strings;
List<List<string>> NewList;

int ListIndex = 0;
for (int i = 0; i < Full.Count; i++)
{
    if (Strings.Contains(Full[i][4]))
    {
        NewList.Add(new List<string>());
        NewList[ListIndex].Add(Full[i][0]);
        NewList[ListIndex].Add(Full[i][1]);
        NewList[ListIndex].Add(Full[i][2]);
        NewList[ListIndex].Add(Full[i][3]);
        NewList[ListIndex].Add(Full[i][4]);
        NewList[ListIndex].Add(Full[i][5]);
        NewList[ListIndex].Add(Full[i][6]);
        NewList[ListIndex].Add(Full[i][7]);
        NewList[ListIndex].Add(Full[i][8]);
        NewList[ListIndex].Add(Full[i][9]);
        ListIndex++;
    }
}

存在的问题

  1. 使用for遍历整个Full的同时,调用Strings.Contains(O(n)复杂度),当Full数据量大、Strings元素较多时,匹配效率极低。
  2. 硬编码逐个添加索引0-9的元素,无法适配子列表元素数量变动的场景。

优化方案

针对上述两个问题,给出两种高效实现方式:

方案1:使用HashSet提升匹配效率 + 动态复制子列表

将Strings转换为HashSet<string>,将元素匹配的时间复杂度从O(n)降至O(1);同时直接复制整个子列表,无需硬编码索引。

实现代码(foreach循环)

// 初始化HashSet,提升匹配速度
var stringLookup = new HashSet<string>(Strings);
var newList = new List<List<string>>();

foreach (var sublist in Full)
{
    // 注意:此处索引需根据实际需求调整,示例中为1,你的代码中为4
    if (stringLookup.Contains(sublist[1]))
    {
        // 动态复制整个子列表,适配任意元素数量
        newList.Add(new List<string>(sublist));
    }
}

方案2:LINQ简化写法

利用LINQ的Where和Select方法,用更简洁的代码实现相同逻辑:

var stringLookup = new HashSet<string>(Strings);
var newList = Full
    .Where(sublist => stringLookup.Contains(sublist[1])) // 筛选符合条件的子列表
    .Select(sublist => new List<string>(sublist)) // 复制子列表
    .ToList();

关键优化点说明

  • 匹配效率提升:HashSet的Contains方法基于哈希表实现,单次判断时间复杂度为O(1),相比List的O(n),在数据量大时性能提升显著。
  • 动态复制子列表:通过new List<string>(sublist)或sublist.ToList()直接复制整个子列表,无需关注子列表的元素数量,完全适配元素数量变动的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:50:24