2

I have converted a hashtable into dictionary. but the problem is when I go to print the values it does not show in sequencing order.

aHashtable.Add(1014, "201");
aHashtable.Add(10, "ATIB");
aHashtable.Add(143, "LOVE");
aHashtable.Add(111, "HATE");

var dict= aHashtable.Cast<DictionaryEntry>().ToDictionary(d => d.Key, d => d.Value);

foreach (KeyValuePair<object, object> keyValuePair in dict)
{
    Console.WriteLine(keyValuePair.Key + ": " +keyValuePair.Value);
}

What's the problem?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Atib
  • 39
  • 3

3 Answers3

5

By default a dictionary is not sorted. C# has a OrderedDictionary though.

See also: The order of elements in Dictionary

Community
  • 1
  • 1
RvdK
  • 19,580
  • 4
  • 64
  • 107
  • I would recommend to use a generic `SortedDictionary` which is easier to convert from a `Dictionary` and avoid boxing when use – Eric Apr 20 '15 at 06:43
  • Depends what the OP wants. SortedDict sorts based on keys. That's different than what OrderedDictionary does. – RvdK Apr 20 '15 at 07:13
0

Dictionaries don't store values based on order of entry.

From docs:

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.

You need an ordered dictionary

See this question.

Community
  • 1
  • 1
0

Please test this code :

var aHashtable = new Hashtable {{1014, "201"}, {10, "ATIB"}, {143, "LOVE"}, {111, "HATE"}};
var dict = aHashtable.Cast<DictionaryEntry> ().ToDictionary(d => d.Key, d => d.Value).OrderBy(x=>x.Key);

foreach (var keyValuePair in dict)
{
    Console.WriteLine(keyValuePair.Key + ": " + keyValuePair.Value);
}
Mohsen
  • 231
  • 5
  • 17