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

如何按条件拼接字符串数组中连续非<p>标签元素?求含/不含LINQ方案

问题:合并数组中连续的非段落标签元素

原始C#字符串数组:

string[] array1 = { 
    "<p>here is a big sentence</p>",
    "file1",
    "file2",
    "<p>this is a big paragraph</p>",
    "file3",
    "file4",
    "file5",
    "<p>this is another paragraph</p>",
};

目标数组:

string[] array2 = { 
    "<p>here is a big sentence</p>",
    "file1,file2",
    "<p>this is a big paragraph</p>",
    "file3,file4,file5",
    "<p>this is another paragraph</p>",
};

需求:将数组中所有不含<p></p>标签的连续字符串拼接为单个元素。


一、不使用LINQ的简洁实现

直接遍历数组,用临时集合缓存连续的非段落元素,遇到段落标签时处理缓存并加入结果:

var result = new List<string>();
var tempFiles = new List<string>();

foreach (var item in array1)
{
    if (item.StartsWith("<p>") && item.EndsWith("</p>"))
    {
        if (tempFiles.Count > 0)
        {
            result.Add(string.Join(",", tempFiles));
            tempFiles.Clear();
        }
        result.Add(item);
    }
    else
    {
        tempFiles.Add(item);
    }
}

// 处理数组末尾可能剩余的非段落元素
if (tempFiles.Count > 0)
{
    result.Add(string.Join(",", tempFiles));
}

string[] array2 = result.ToArray();

思路:用临时列表存连续的文件元素,遇到段落标签时先把缓存的文件拼接后加入结果,再添加当前段落;遍历结束后检查缓存,避免遗漏末尾的文件组。


二、使用LINQ的简洁实现

利用Aggregate方法逐步构建结果,直接在遍历中合并连续的文件元素:

var array2 = array1.Aggregate(new List<string>(), (list, item) =>
{
    if (item.StartsWith("<p>") && item.EndsWith("</p>"))
    {
        list.Add(item);
    }
    else
    {
        if (list.Count == 0 || list.Last().StartsWith("<p>"))
        {
            list.Add(item);
        }
        else
        {
            list[list.Count - 1] += $",{item}";
        }
    }
    return list;
}).ToArray();

思路:用Aggregate维护结果列表,遇到段落元素直接添加;遇到文件元素时,若列表最后一项是段落则新建项,否则直接追加到最后一项末尾。


关于标准实现方案

.NET标准库中没有专门针对这种「连续同类元素合并」的现成方法,但上述两种方式都是这类序列处理场景的常规实现:通过遍历/聚合时维护状态,对连续的目标元素进行合并,属于通用的序列处理模式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:26:19