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

C#中如何合并列表除首尾元素对外的中间对并求和以缩短列表长度

实现方案

前提说明

处理前请确保输入列表长度为偶数,否则无法按两两分组规则正常处理。

方案1:单LINQ链式写法

直接通过一次LINQ链式调用完成处理,用到Select、GroupBy、SelectMany等方法:

List<double> source = new List<double> { 12.0, 10.0, 19.0, 34.0, 16.0, 12.0, 99.0, 68.0 };

if (source.Count % 2 != 0)
    throw new ArgumentException("输入列表长度必须为偶数");

var result = source
    .Select((value, index) => new { Value = value, GroupId = index / 2 })
    .GroupBy(x => x.GroupId)
    .SelectMany((group, groupIndex) =>
    {
        int totalGroups = source.Count / 2;
        // 首尾分组直接保留两个元素
        if (groupIndex == 0 || groupIndex == totalGroups - 1)
            return group.Select(x => x.Value);
        // 中间分组求和后返回单个元素
        return new[] { group.Sum(x => x.Value) };
    })
    .ToList();

方案2:GetRange拆分写法

逻辑更直观,拆分首尾和中间部分分别处理,符合GetRange方法的使用要求:

List<double> source = new List<double> { 12.0, 10.0, 19.0, 34.0, 16.0, 12.0, 99.0, 68.0 };
int totalCount = source.Count;

if (totalCount % 2 != 0)
    throw new ArgumentException("输入列表长度必须为偶数");

// 取首组两个元素
List<double> firstPair = source.GetRange(0, 2);
// 取中间需要合并的所有元素
List<double> middlePart = source.GetRange(2, totalCount - 4);
// 中间部分两两求和
List<double> mergedMiddle = middlePart
    .Select((value, index) => new { Value = value, GroupId = index / 2 })
    .GroupBy(x => x.GroupId)
    .Select(g => g.Sum(x => x.Value))
    .ToList();
// 取尾组两个元素
List<double> lastPair = source.GetRange(totalCount - 2, 2);

// 拼接得到最终结果
List<double> result = firstPair.Concat(mergedMiddle).Concat(lastPair).ToList();

其他说明

两种方案针对示例输入的输出均为[12.0, 10.0, 53.0, 28.0, 99.0, 68.0],完全符合需求。如果需要修改原列表而非生成新列表,可追加以下代码:

source.Clear();
source.AddRange(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:09:04