简体   繁体   中英

Iterate N numbers and do a sum on it using LINQ

Is there a possible way to iterate N-numbers in LINQ to get a sum on it?

for instance:

var n = 3;

//The part I wonder about if you can do this entirely with LINQ
var t = 0;
for (var i = 0; i < n; i++){ 
    t += i;
}

Just use Enumerable.Range to generate your list of numbers then Sum them

var n = 3;
var sum = Enumerable.Range(0, n).Sum();
int sum = Enumerable.Range(0, n).Sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM