ada7ke
ada7ke

Reputation: 87

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

Upvotes: 1

Views: 1671

Answers (4)

Thomas Weller
Thomas Weller

Reputation: 59303

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.

Upvotes: 6

ekolis
ekolis

Reputation: 6786

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);

Upvotes: 4

gunr2171
gunr2171

Reputation: 17520

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.

Upvotes: 1

yassinMi
yassinMi

Reputation: 737

var list = Enumerable.Range(0,10).Select(i=>{Console.WriteLine(i); return i; });

Upvotes: 0

Related Questions