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))
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With