Say, if I create a dictionary like this:
Dictionary<string, MyClass> dic = new Dictionary<string, MyClass>();
dic.add("z1", val1);
dic.add("abc9", val2);
dic.add("abc8", val3);
dic.add("ABC1", val4);
So when I do:
foreach (KeyValuePair<string, MyClass> kvp in dic)
{
}
Am I guaranteed to have these values retrieved as such: "z1", "abc9", "abc8", "ABC1"?
And what if I first do this, will it be: "z1", "abc8", "ABC1"?
dic.Remove("abc9");
[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
In a SortedDictionary<TKey,TValue> the keys and values are maintained in order by the value of the key - this is not the same as insertion order. The only built-in dictionary in the . NET framework that preserves insertion order is System. Collections.
In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements.
In C#, SortedDictionary is a generic collection which is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System.
No. From MSDN (emphasis mine)
For purposes of enumeration, each item in the dictionary is treated as a
KeyValuePair<TKey, TValue>
structure representing a value and its key. The order in which the items are returned is undefined.
You may want to look at the OrderedDictionary class if you want more control over the iteration order.
The short answer is No. Order is not guaranteed in a Dictionary<TKey, TValue>
, nor should you count on order being maintained.
You might want to check into OrderedDictionary
instead.
Example:
OrderedDictionary d = new OrderedDictionary();
d.Add("01", "First");
d.Add("02", "Second");
d.Add("03", "Third");
d.Add("04", "Fourth");
d.Add("05", "Fifth");
for(int i = 0; i < d.Count; i++) // Print values in order
{
Console.WriteLine(d[i]);
}
Note there's no generic OrderedDictionary<TKey,TValue>
version for some odd reason. However, this question has some hints on how to implement one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With