Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have List(T).ForEach() that traverses elements strictly in order?

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()?

like image 233
sharptooth Avatar asked Jul 06 '11 09:07

sharptooth


People also ask

Does forEach go in order?

Calls the given closure on each element in the sequence in the same order as a for - in loop.

Does forEach run sequentially?

ForEach-Object has no parallelism. It executes each loop sequentially.

Can you use forEach on a list?

forEach statement is a C# generic statement which you can use to iterate over elements of a List.

Does forEach guarantee order Java?

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.


3 Answers

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

like image 154
Jon Skeet Avatar answered Sep 27 '22 02:09

Jon Skeet


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.

like image 21
Alex Avatar answered Sep 24 '22 02:09

Alex


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.

like image 20
Tomas Vana Avatar answered Sep 27 '22 02:09

Tomas Vana