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

C#循环中如何追加过滤数据到新数组而非重置数组?

循环中保留过滤数据并追加的解决方案

问题根源

你代码里的splitArray在每次循环时都会被重新赋值,之前处理的结果完全被覆盖,自然无法保留历史数据。要实现追加,必须用一个支持动态添加的外部集合,而不是每次重新创建数组。

修改后的完整代码

public override void Select()
{
    StringBuilder sb = new StringBuilder($"{MenuText()}{Environment.NewLine}");
    int i = 1;
    foreach (string file in _reader.paths)
    {
        sb.AppendLine($"{i}. {file}");
        i++;
    }
    Console.WriteLine(sb.ToString());
    int selectedIndex = ConsoleHelpers.GetIntegerInRange(1, _reader.paths.Count, MenuText()) - 1;
    string[] result = File.ReadAllLines(_reader.paths[selectedIndex]);
    if (result.Length == 0)
    {
        Console.WriteLine("Cannot open file - No data found");
    }
    else
    {
        // 声明全局集合存储所有过滤后的内容,支持动态追加
        List<string> filteredContent = new List<string>();
        foreach (string line in result)
        {
            // 分割字符串、去除首尾空格、过滤空元素
            var processedLine = line.Split(':')
                                   .Select(s => s.Trim())
                                   .Where(x => !string.IsNullOrEmpty(x))
                                   .ToArray();
            // 将当前行处理后的所有元素追加到集合
            filteredContent.AddRange(processedLine);
        }
        // 如需转成数组格式,执行以下代码
        string[] finalFilteredArray = filteredContent.ToArray();
        // 这里可以添加对finalFilteredArray的后续操作
    }
}

关键修改点

  • 替换原局部数组为外部List<string>集合:确保每次循环的结果能被持久存储,不会被覆盖
  • 使用AddRange批量追加元素:一次性把当前行处理后的所有元素加入集合,比逐个Add更高效
  • 可选转数组:如果业务需要数组格式,最后调用ToArray()即可完成转换

扩展场景(可选)

如果需要保留每行的独立数据(比如生成二维数组),可以把集合类型改为List<string[]>,然后用filteredContent.Add(processedLine)替代AddRange,这样每行的处理结果会作为单独的数组项存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:06:00