How to subract every element in an array from each other in C#?

70 views Asked by At

I want to subrtract every element from each other, kind of like this:

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

And the desired output being:

6

How would this be done? Is there a simple way of doing this?

1

There are 1 answers

0
Mateus Zampol On

You can use Linq:

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

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

Console.WriteLine(result); // 6