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

如何用C# Enumerable.Aggregate方法返回含累加和的对象列表?

使用Enumerable.Aggregate实现累加和生成ObjectB列表

首先定义实体类:

public class ObjectA
{
    public int Value { get; set; }
}

public class ObjectB
{
    public int Sum { get; set; }
}

实现方式一:用匿名类型作为聚合状态

通过Aggregate跟踪当前累加总和与结果列表,每一步迭代生成对应的ObjectB并加入列表:

List<ObjectA> listA = new List<ObjectA>
{
    new ObjectA { Value = 1 },
    new ObjectA { Value = 2 },
    new ObjectA { Value = 3 },
    new ObjectA { Value = 4 },
    new ObjectA { Value = 5 },
    new ObjectA { Value = 6 }
};

List<ObjectB> listB = listA.Aggregate(
    // 初始状态:累加和为0,结果列表为空
    new { CurrentSum = 0, Result = new List<ObjectB>() },
    // 迭代逻辑:更新累加和,生成ObjectB并加入列表
    (accumulator, currentA) =>
    {
        int newSum = accumulator.CurrentSum + currentA.Value;
        accumulator.Result.Add(new ObjectB { Sum = newSum });
        return new { CurrentSum = newSum, Result = accumulator.Result };
    },
    // 最终提取结果列表
    accumulator => accumulator.Result
);

实现方式二:自定义聚合状态类

如果觉得匿名类型不够直观,可以自定义状态类管理累加和与结果:

public class AggregationState
{
    public int CurrentSum { get; set; }
    public List<ObjectB> ResultList { get; } = new List<ObjectB>();
}

// 调用Aggregate
List<ObjectB> listB = listA.Aggregate(
    new AggregationState(),
    (state, currentA) =>
    {
        state.CurrentSum += currentA.Value;
        state.ResultList.Add(new ObjectB { Sum = state.CurrentSum });
        return state;
    },
    state => state.ResultList
);

两种方式都能实现预期效果:输入Value为{1,2,3,4,5,6}的ObjectA列表时,输出Sum为{1,3,6,10,15,21}的ObjectB列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 19:30:55