如何在 C# 中将数组中的每个元素相减?

问题描述 投票:0回答:1

我想将每个元素相减,有点像这样:

List<int> list = [20, 4, 3, 7];
list = SubtractAll(list); // 20 - 4 - 3 - 7

期望的输出是:

6

这将如何完成?有没有简单的方法可以做到这一点?

c# list math subtraction
1个回答
0
投票

您可以使用 Linq:

List<int> list = [20, 4, 3, 7];

var result = list.Aggregate((curr, next) => curr - next);

Console.WriteLine(result); // 6
© www.soinside.com 2019 - 2024. All rights reserved.