Home > Mobile >  Can you make for loops in one line in c#?
Can you make for loops in one line in c#?

Time:07-30

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

CodePudding user response:

Yes, you can:

var myList = from x in Enumerable.Range(0, 10) select x;

The term in Python is list comprehension. I don't think it has a special name in C#, except the general concept called LINQ.

As for your original code

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

The content of myList like that will be [None, None, None, None, None, None, None, None, None, None] because print() does not return anything. I guess that's not intended. If you really want that, you can go with

var myList = Enumerable.Range(0, 10).Select<int,object>(x=>{Console.WriteLine(x); return null; });

Be aware that LINQ has lazy evaluation, so the Console output may not appear until you use the list, unlike Python, which if I recall correctly prints right away.

CodePudding user response:

Yes, if there is only one statement inside the loop, you can put it on the same line:

foreach (var x in Enumerable.Range(0, 10)) Console.WriteLine(x);

CodePudding user response:

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.

CodePudding user response:

var list = Enumerable.Range(0,10).Select(i=>{Console.WriteLine(i); return i; });
  •  Tags:  
  • c#
  • Related