Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are elements in a .NET's Dictionary sequential? [duplicate]

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");
like image 720
ahmd0 Avatar asked Sep 26 '13 21:09

ahmd0


People also ask

Can C# Dictionary have duplicate values?

[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<> .

Is order maintained in dictionary C#?

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.

Does C# dictionary allow duplicate keys?

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.

Are Dictionaries sorted C#?

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.


2 Answers

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.

like image 68
keyboardP Avatar answered Oct 05 '22 22:10

keyboardP


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.

like image 40
Mike Christensen Avatar answered Oct 05 '22 23:10

Mike Christensen