I need to store a list of int–string key-value pairs with a requirement to preserve the order in which items were added. Once it is initialized, it does not change, i.e. nothing added or removed..
At first I thought of using Dictionary<int,string> and everytime I need to access the items use
foreach(var entry in dict.OrderBy(e=>e.Key)) { } //as Key is `int`
However everytime ordering does not seem to be the best option to use.
Now I’ve come to an idea to have a List<Tuple<int, string>>, as soon as List<T> guarantees the order of items.
So, is there a better option?
Looking at the proposed possibilities:
Dictionarydoesn’t guarantee the order of the itemsSortedDictionarysorts the items, but not in the order you added them (it sorts based on key comparison),OrderedDictionarykeeps the order, but it’s not generic and would introduce unnecessary casting and boxing.So I think you should use
List<Tuple<int, string>>. It preserves order and it’s good enough for iteration usingforeachand indexed access. If you know the size in advance, you could use an array as well, or a read only collection type, as Cuong Le suggested in his answer.