Accumulating amount in one line in C #

Is it possible to do this on one line in order to get the accumulated amount equal to n?

int n = 0; for (int i = 1; i <= 10; i++) { n += i; } 
+7
source share
5 answers

There is a LINQ extension method for this:

 static int SlowSum1ToN(int N) { return Enumerable.Range(1, N).Sum(); } 

However, you can also calculate this specific value (the sum of an arithmetic sequence) without iterating at all :

 static int FastSum1ToN(int N) { return (N * (1 + N)) / 2; } 
+14
source

Yes

You can replace

 int S = 0 for (int i = 0; i <= N; i++) { S += i; } 

from

int S = (N*(N+1))/2

+5
source

Yes, it is possible, you can do this with Enumerable.Range to generate a sequence of integers, and then call the LINQ Sum extension method as follows:

 int result = Enumerable.Range(1, 10).Sum(); 
+4
source

As an added answer, there is also an Aggregate function, more general than Sum :

 var sum = Enumerable.Range(1, 10).Aggregate(0, (a, b) => a += b); 

So, you can also do things like

 // multiply 1 * 2 * 3 * 4 ... var product = Enumerable.Range(1, 10).Aggregate(1, (a, b) => a *= b); 
+1
source

What is a hobby for one liner? Here he is:

int n = 0; for (int i = 1; i <= 10; i++) {n += i;}

Is there a better way to calculate this? Of course. See Other Answers that use the formula.

0
source

All Articles