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

如何用单条LINQ语句折叠C#带引号字符串数组并去除引号?

用单条LINQ语句实现数组折叠与引号去除

这是个很巧妙的分组拼接场景,刚好能用LINQ的Aggregate方法完成单语句解决方案,核心是通过累积状态来跟踪是否处于「合并模式」:

string[] arr = new[] {"a", "b", "\"b", "c\"", "c"};

var foldedArr = arr.Aggregate(
    new { Result = new List<string>(), CurrentGroup = (string)null },
    (accumulator, item) =>
        accumulator.CurrentGroup == null
            ? item.StartsWith("\"")
                ? new { accumulator.Result, CurrentGroup = item.TrimStart('"') }
                : new { Result = accumulator.Result.Append(item).ToList(), CurrentGroup = (string)null }
            : item.EndsWith("\"")
                ? new { Result = accumulator.Result.Append($"{accumulator.CurrentGroup} {item.TrimEnd('"')}").ToList(), CurrentGroup = (string)null }
                : new { accumulator.Result, CurrentGroup = $"{accumulator.CurrentGroup} {item}" },
    finalState => finalState.Result.ToArray()
);

逻辑拆解

  1. 初始状态:用匿名类型作为Aggregate的种子,包含两个核心属性:

    • Result:存储最终输出的列表容器
    • CurrentGroup:跟踪当前正在合并的字符串段(初始为null,表示未进入合并模式)
  2. 逐个处理元素:

    • 若未处于合并模式:
      • 元素以"开头时,去掉开头引号并将其设为CurrentGroup,进入合并状态
      • 否则直接把元素加入结果列表
    • 若处于合并模式:
      • 元素以"结尾时,去掉结尾引号,和CurrentGroup用空格拼接后加入结果,同时退出合并状态
      • 否则把当前元素用空格拼接到CurrentGroup后,继续累积内容
  3. 最终转换:把累积的结果列表转为数组,就是你需要的输出。

验证结果

针对你给出的输入数组,执行后foldedArr的结果正好是:{"a", "b", "b c", "c"},完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:30:39