In what order does a C# for each loop iterate over a List?

前端 未结 6 1227
南旧
南旧 2020-12-03 00:35

I was wondering about the order that a foreach loop in C# loops through a System.Collections.Generic.List object.

I found another question abou

6条回答
  •  难免孤独
    2020-12-03 00:58

    Basically it's up to the IEnumerator implementation - but for a List it will always go in the natural order of the list, i.e. the same order as the indexer: list[0], list[1], list[2] etc.

    I don't believe it's explicitly documented - at least, I haven't found such documentation - but I think you can treat it as guaranteed. Any change to that ordering would pointlessly break all kinds of code. In fact, I'd be surprised to see any implementation of IList which disobeyed this. Admittedly it would be nice to see it specifically documented...

提交回复
热议问题