Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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#?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading