Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach/For loop alternative lambda function?

Tags:

c#

We use for or foreach to loop through collections and process each entries.

Is there any alternative in all those new lambda functions for collections in C#?

Traditional way of doing

foreach(var v in vs)
{
  Console.write(v);
}

Is there anything like?

vs.foreach(v => console.write(v))
like image 389
mamu Avatar asked Apr 23 '10 14:04

mamu


People also ask

What can I use instead of forEach in Java?

for Loop vs foreach Loop The for loop is a control structure for specifying iteration that allows code to be repeatedly executed. The foreach loop is a control structure for traversing items in an array or a collection. A for loop can be used to retrieve a particular set of elements.

Is forEach better than for loop Java?

forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.

What can I use instead of forEach?

The every() function is a good alternative to forEach, let us see an example with a test implementation, and then let's return out of the every() function when a certain condition meet.


1 Answers

List has the ForEach method, however, IEnumerable does not.

There are a number of questions / answers regarding this. I think the main reason it was not implemented in IEnumerable though is that Linq on Enumerables is "meant" to be side effect free as it's a querying language.

Eric Lippert explains his thoughts on his blog.

http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx

like image 129
Robin Day Avatar answered Sep 22 '22 07:09

Robin Day