There's List(T).ForEach()
that performs an action on each element of the list. However MSDN description doesn't say anything about the order in which List
elements will be traversed and I need to have them traversed strictly in order.
How can I achieve that with ForEach()
?
Calls the given closure on each element in the sequence in the same order as a for - in loop.
ForEach-Object has no parallelism. It executes each loop sequentially.
forEach statement is a C# generic statement which you can use to iterate over elements of a List.
For parallel streams, forEach() operation does not guarantee to respect the encounter order of the Stream. While the forEachOrdered() operation respects the encounter order of the stream if the stream has a defined encounter order. This behavior is also true for parallel streams as well as sequential streams.
List<T>.ForEach
will go in the same order as a normal foreach
loop, which is also the natural order of the list.
Yes, the documentation doesn't state it - but it's the obvious behaviour, and I think it's pretty reasonable to rely on that not changing.
(Now Parallel.ForEach
is a different matter, of course.)
If the order of the elements is essential I would recommend to use a Queue<T>
(LIFO) or a Stack<T>
(FIFO) which ensure the order by design. In this case you have to use a classic loop instead using the LINQ extension method or implement it by yourself.
The List<T>
class represents an ordered collection of items, so iterating it using enumerators or ForEach
method will preserve the order, even if the documentation is not very clear on this.
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