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 开发者_JAVA百科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()
?
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.
精彩评论