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?
By default a dictionary is not sorted. C# has a OrderedDictionary though.
See also: The order of elements in Dictionary
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 .
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.