如何用单条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() );
逻辑拆解
初始状态:用匿名类型作为
Aggregate的种子,包含两个核心属性:Result:存储最终输出的列表容器CurrentGroup:跟踪当前正在合并的字符串段(初始为null,表示未进入合并模式)
逐个处理元素:
- 若未处于合并模式:
- 元素以
"开头时,去掉开头引号并将其设为CurrentGroup,进入合并状态 - 否则直接把元素加入结果列表
- 元素以
- 若处于合并模式:
- 元素以
"结尾时,去掉结尾引号,和CurrentGroup用空格拼接后加入结果,同时退出合并状态 - 否则把当前元素用空格拼接到
CurrentGroup后,继续累积内容
- 元素以
- 若未处于合并模式:
最终转换:把累积的结果列表转为数组,就是你需要的输出。
验证结果
针对你给出的输入数组,执行后foldedArr的结果正好是:{"a", "b", "b c", "c"},完全匹配需求。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

