How to print 1 to 100 without any looping using C#

后端 未结 28 1519
天命终不由人
天命终不由人 2020-12-22 19:30

I am trying to print numbers from 1 to 100 without using loops, using C#. Any clues?

28条回答
  •  佛祖请我去吃肉
    2020-12-22 20:11

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

    Here's a breakdown of what is happening in the above code:

    • Enumerable.Range returns the specified range of integral numbers as IEnumerator
    • Enumerable.ToList converts an IEnumerable into a List
    • List.ForEach takes a lamdba function and invokes it for each item in the list

    Performance Consideration

    The ToList call will cause memory to be allocated for all items (in the above example 100 ints). This means O(N) space complexity. If this is a concern in your app i.e. if the range of integers can be very high, then you should avoid ToList and enumerate the items directly.

    Unfortunately ForEach is not part of the IEnumerable extensions provided out of the box (hence the need to convert to List in the above example). Fortunately this is fairly easy to create:

    static class EnumerableExtensions
    {
        public static void ForEach(this IEnumerable items, Action func)
        {
            foreach (T item in items)
            {
                func(item);
            }
        }
    }
    

    With the above IEnumerable extension in place, now in all the places where you need to apply an action to an IEnumerable you can simply call ForEach with a lambda. So now the original example looks like this:

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

    The only difference is that we no longer call ToList, and this results in constant (O(1)) space usage... which would be a quite noticeable gain if you were processing a really large number of items.

提交回复
热议问题