Get a continuous list of integers

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

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

But I remember one line of code that I myself used before. As below:

Enumerable.TheMethodGives1To1000(Console.WriteLine);

Any ideas?

+4
source share
3 answers

You need a Enumerable.Rangemethod that generates a sequence of integers in the specified range. It returns an object IEnumerable<int>. And for printing elements in this collection we can use the method List<T>.ForEach. It performs the specified action for each item List<T>. And in the case of a single argument, you can pass the function yourself.

So the result is:

 Enumerable.Range(1, 1000)
           .ToList()
           .ForEach(Console.WriteLine);
+14
source
foreach(var i in Enumerable.Range(1, 999))
    Console.WriteLine(i);
+2
source

Enumerable.Range.

The Console.WriteLinq query call is somewhat unusual since it does not return a value.

You can build the string first and then print it i, e:

var result = String.Join("\n", Enumerable.Range(1,10).Select(i=> i.ToString()));

Or use ForEachforList

Enumerable.Range(1,10).ToList().ForEach(Console.WriteLine)

Or return the value with the call WriteLineto Select:

Enumerable.Range(1,10).Select(i => { Console.WriteLine(i); return 0;});
+1
source

Source: https://habr.com/ru/post/1535477/


All Articles