Reputation: 8564
I've always thought otherwise, but recently I had the need to know:
If I add elements to a list in a certain order, am I guaranteed to find then always on the same order?
Thanks!
Upvotes: 15
Views: 5584
Reputation: 29399
Yes, it is deterministic. Bear in mind that if you want to use List<T>
across threads then, as with anything, you can't guarantee the order in which the interactions would happen.
Upvotes: 8
Reputation: 71593
Yes. List is an indexed collection; using Add() to put elements into the List will cause them to be indexed in the order they're added.
Upvotes: 3
Reputation: 54764
Yes; you control the ordering of a List<T>
.
You can assume that any .NET collection with a list[int]
indexer has a predictable ordering; otherwise, the numerical index wouldn't make any sense. By comparison, it's not possible to use a numerical index with a Dictionary<K,V>
, and when you enumerate a dictionary, the ordering isn't guaranteed.
Upvotes: 33