How to print numbers using LINQ

I am trying to print natural numbers from 1 to 100 with LINQ and without any cycles. The requested LINQ query does not even compile.

Console.WriteLine(from n in Enumerable.Range(1, 100).ToArray()); 

Please help me.

+6
source share
5 answers

Method Syntax:

 Enumerable.Range(1, 100).ToList().ForEach(Console.WriteLine); 

Request syntax:

 (from n in Enumerable.Range(1, 100) select n) .ToList().ForEach(Console.WriteLine); 

Or if you need a comma separated list:

 Console.WriteLine(string.Join(",", Enumerable.Range(1, 100))); 

In this case, the String.Join <T> (String, IEnumerable <T>) overload introduced in .NET 4.0 is used.

+15
source

Your LINQ query is almost close to a solution, only some tuning is required.

 Console.WriteLine(String.Join(", ", (from n in Enumerable.Range(1, 100) select n.ToString()).ToArray())); 

Hope this helps

+4
source

Try the following:

 Enumerable.Range(1, 100).ToList().ForEach(x => Console.WriteLine(x)); 

You can also add ForEach as an extension method for IEnumerable instead of first converting to a list if you want to improve performance a bit.

+1
source

It is not possible to move through an array without any loops; you can use the ForEach extension method for the List class.

 Enumerable.Range(1,100).ToList().ForEach( i => Console.WriteLine(i)); 

I don’t know why you would like to do this, but the loop may not be written by you, but it will eventually be presented in some part of the code.

EDIT: Any solution presented will have some loop or even two, if you just want to iterate over all elements, you must create an extension in which you hide for each

  public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) { if (action == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } foreach(T item in enumeration) { action(item); } } 
0
source

LINQ is a query language. It can only filter and convert data. This is what LINQ is for. Of course, there will be some ForEach extension, but this is not part of LINQ itself.

And just to fix you, there are loops in LINQ, except that they are hidden from your view.

0
source

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


All Articles