开发者

How to print numbers using LINQ

I am trying to print natural numbers from 1 to 100 using LINQ and without any loo开发者_如何学运维ps. The LINQ query I wrote doesn't even compile at all.

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

Please help me.


Method syntax:

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

Query syntax:

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

Or, if you want a comma separated list:

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

This one uses the String.Join<T>(String, IEnumerable<T>) overload introduced in .NET 4.0.


Your LINQ query is almost near to the solution, only some tweaking is needed.

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

Hope this helps


Try this:

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

You can also add ForEach as an extension method to IEnumerable instead of having to convert to list first, if you desire a little better performance.


LINQ is query language. It can only filter and transform data. That what LINQ is inteded for. Of course there will be some ForEach extension, but that is not part of LINQ itself.

And just to correct you, there are loops in LINQ, except they are hidden from your sight.


It is imposible to walko over an array without any loops, you can use the ForEach extention method for List class.

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

I dont know why you would like do this, but the loop might not be writen by you but eventually in some part of code will be presented.

EDIT: Any solution presented will have somewhere some loop or even two, if you just want to iterate through all elements, you should create an extension where you hide the 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜