I am trying to print numbers from 1 to 100 without using loops, using C#. Any clues?
Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(i));
Here's a breakdown of what is happening in the above code:
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.