Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?
First, let me specify I am refering to the List<T>
method and not the C# keyword. What would be Microsoft's reasoning for having the Foreach method on the List<T>
collection but no other collection/enumerable type, specifically IEnumerable<T>
?
I just discovered this method the other day, and found it to be very nice syntax for replacing traditional foreach loops that only perform one or 2 lines of methods on each object.
It seems like it would be fairly trivial to create an extension method that ,performs this same function. I guess I'm looking at why MS made this decision and based on that if I should just make an extension method.
forEach statement is a C# generic statement which you can use to iterate over elements of a List.
forEach() does not make a copy of the array before iterating.
How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.
Answers. Yes. An (IList) is ordered, and iterating will iterate from the first item to the last, in order inserted (assuming you always inserted at the end of the list as opposed to somewhere else, depending on the methods you used).
Eric Lippert has responded to this question numerous times, including on his blog.
His response has been that ForEach()
is something you use explicitly for its side effects - whereas LINQ is largely intended to be a side-effect free API to define projections and manipulations on sequences.
Outside of uses like parallel loops, the functional ForEach
syntax doesn't add much in the way of expressive power, and it is slightly less efficient than a regular foreach
loop due to the delegate invocations.
If you really, really want a ForEach
for IEnumerable<T>
, it's not hard to write one:
public static class ForEachExtension
{
public static void ForEach<T>( this IEnumerable<T> seq, Action<T> action )
{
foreach( var item in seq )
action( item );
}
// Here's a lazy, streaming version:
public static IEnumerable<T> ForEachLazy<T>( this IEnumerable<T> seq, Action<T> action )
{
foreach( var item in seq )
{
action( item );
yield return item;
}
}
}
Read the answer from the man who helped design the compiler .. 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