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

如何在C#中实现集合内所有元素依次相减?

实现集合元素依次相减的几种方法

基础循环实现

这种方式逻辑直观,适合理解底层运算过程:

public static int SubtractAll(List<int> list)
{
    if (list == null || list.Count == 0)
        throw new ArgumentException("集合不能为空");
    if (list.Count == 1)
        return list[0];
    
    int result = list[0];
    for (int i = 1; i < list.Count; i++)
    {
        result -= list[i];
    }
    return result;
}

思路:先做参数校验,空集合直接抛出异常;如果只有单个元素,直接返回该元素。从第一个元素开始,遍历后续所有元素依次相减,最终得到结果。

LINQ简便实现

用LINQ的Aggregate方法可以简化核心逻辑,代码更紧凑:

using System.Linq;

public static int SubtractAll(List<int> list)
{
    if (list == null || list.Count == 0)
        throw new ArgumentException("集合不能为空");
    
    return list.Aggregate((current, next) => current - next);
}

Aggregate会自动执行累积运算:对于示例中的[20,4,3,7],先计算20-4=16,接着用16减去3得到13,最后13减7得到6,完全符合需求。如果集合只有单个元素,Aggregate会直接返回该元素,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:05:57