Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get continuous list of integers

Tags:

c#

.net

I am trying to print numbers from 1 to 1000 (inclusive of 1000).

for (int i = 1; i <= 1000; i=i+1)
{
       Console.WriteLine(i);
}

But, I do remember a single line of code that I myself used before. Like below:

Enumerable.TheMethodGives1To1000(Console.WriteLine);

Any ideas ?

like image 421
now he who must not be named. Avatar asked Dec 02 '22 20:12

now he who must not be named.


2 Answers

What you need is Enumerable.Range method which generates a sequence of integral numbers within a specified range. It returns IEnumerable<int> object. And for printing the elements in this collection we can use List<T>.ForEach method. It performs the specified action on each element of the List<T>. And in case of single argument you can pass function by itself.

So, the result is:

 Enumerable.Range(1, 1000)
           .ToList()
           .ForEach(Console.WriteLine);
like image 178
Farhad Jabiyev Avatar answered Dec 22 '22 00:12

Farhad Jabiyev


foreach(var i in Enumerable.Range(1, 999))
    Console.WriteLine(i);
like image 34
Aron Avatar answered Dec 21 '22 22:12

Aron