I need to store a list of key value pairs of (integer, boolean) in .NET
When I use a dictionary it re-orders them. Is there a built in collection that will handle this.
I need to store a list of key value pairs of (integer, boolean) in .NET
When I use a dictionary it re-orders them. Is there a built in collection that will handle this.
List<KeyValuePair<int, bool>> l =
new List<KeyValuePair<int, bool>>();
l.Add(new KeyValuePair<int, bool>(1, false));
If you want to preserve insertion order, why not use a Queue?
http://msdn.microsoft.com/en-us/library/6tc79sx1(VS.71).aspx
A Dictionary reorders the elements for faster lookup. Preserving insertion order would defeat that purpose...
You could just create a list of KeyValuePairs:
var myList = new List<KeyValuePair<int, bool>>();
The dictionary is supposed to reorder them, the a map by itself has no notion of order.
There is a class in .Net that supports that notion:
SortedDictionary<Tkey, Tvalue>
it requires that the Tkey type implements de IComparable interface so it known how to sort items. This way when your return the keys or the values they should be in the order the IComparable implementation specifies. For integers of course that is a trivial:
a < b
OrderedDictionary is the way to go. It provides O(1) retreival and O(n) insert. For more detailed info see codeproject
What about an array?
KeyValuePair<int, bool>[] pairs
A list might be more useful when you want to add pairs after initialization of the collection.
List<KeyValuePair<int, bool>>