Can you make for loops in one line in c#?

Advertisements

In python, you can write for loops in one line such as:

myList = [print(x) for x in range(10)]

Can you do something similar in c#?

>Solution :

While I don’t really recommend it, a List has a ForEach method, which lets you execute an action on each element. I don’t recommend this because LINQ is intended for actions that don’t cause side effects. ForEach can cause side effects.

Enumerable.Range(0, 10).ToList().ForEach(x => Console.WriteLine(x));

// or slightly shorter without the lambda, same thing
Enumerable.Range(0, 10).ToList().ForEach(Console.WriteLine);

I’d much rather go with a foreach loop. Linq’s not the best when it comes to something other than querying data.

Leave a ReplyCancel reply