The order of elements in Dictionary

My question is about enumerating Dictionary elements

// Dictionary definition
private Dictionary<string, string> _Dictionary = new Dictionary<string, string>();


// add values using add


_Dictionary.Add("orange", "1");
_Dictionary.Add("apple", "4");
_Dictionary.Add("cucumber", "6");


// add values using []


_Dictionary["banana"] = 7;
_Dictionary["pineapple"] = 7;


// Now lets see how elements are returned by IEnumerator
foreach (KeyValuePair<string, string> kvp in _Dictionary)
{
Trace.Write(String.Format("{0}={1}", kvp.Key, kvp.Value));
}

In what order will be the elements enumerated? Can I force the order to be alphabetical?

115275 次浏览

The order of elements in a dictionary is non-deterministic. The notion of order simply is not defined for hashtables. So don't rely on enumerating in the same order as elements were added to the dictionary. That's not guaranteed.

Quote from the doc:

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.

Associative arrays (aka, hash tables) are unordered, which means that the elements can be ordered in any way imaginable.

HOWEVER, you could fetch the array keys (only the keys), order that alphabetically (via a sort function) and then work on that.

I cannot give you a C# sample because I don't know the language, but this should be enough for you to go on yourself.

If you want the elements ordered, use a SortedDictionary. An ordinary hastable/dictionary is ordered only in some sense of the storage layout.

The items will be returned in the order that they happen to be stored physically in the dictionary, which depends on the hash code and the order the items were added. Thus the order will seem random, and as implementations change, you should never depend on the order staying the same.

You can order the items when enumerating them:

foreach (KeyValuePair<string, string> kvp in _Dictionary.OrderBy(k => k.Value)) {
...
}

In framework 2.0 you would first have to put the items in a list in order to sort them:

List<KeyValuePair<string, string>> items = new List<KeyValuePair<string, string>>(_Dictionary);
items.Sort(delegate(KeyValuePair<string, string> x, KeyValuePair<string, string> y) { return x.Value.CompareTo(y.Value); });
foreach (KeyValuePair<string,string> kvp in items) {
...
}

You can always use SortedDictionary for that. Note that the dictionary is ordered by Key, by default, unless a comparer has been specified.

I'm skeptic regarding the use of OrderedDictionary for what you want since documentation says that:

The elements of an OrderedDictionary are not sorted by the key, unlike the elements of a SortedDictionary class.

For an OrderedDictionary:

 var _OrderedDictionary = new System.Collections.Specialized.OrderedDictionary();


_OrderedDictionary.Add("testKey1", "testValue1");
_OrderedDictionary.Add("testKey2", "testValue2");
_OrderedDictionary.Add("testKey3", "testValue3");


var k = _OrderedDictionary.Keys.GetEnumerator();
var v = _OrderedDictionary.Values.GetEnumerator();


while (k.MoveNext() && v.MoveNext()) {
var key = k.Current; var value = v.Current;
}

Items are returned in the order that they are added.