This program is given in the following website. Following output is expected because elements are in this order in Add() method. But vice versa output of this order is returned. Please explain the reason. Problem is coloured.
http://www.dotnetperls.com/dictionaryentry
1 = one
2 = two
3 = three
using System;
using System.Collections;
class Program
{
static void Main()
{
// Create hashtable with some keys and values.
Hashtable hashtable = new Hashtable();
hashtable.Add(1, "one");
hashtable.Add(2, "two");
hashtable.Add(3, "three");
// Enumerate the hashtable.
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0} = {1}", entry.Key, entry.Value);
}
Console.ReadKey();
}
}
/*
3 = three
2 = two
1 = one
*/
Loading
VulpesPosted Sep 12, 2013, 9:15 AM
Consequently, when you enumerate the Hashtable, the order in which the DictionaryEntry instances are returned is unpredictable.
There is something called an OrderedDictionary which does return the DictionaryEntry instances in the order they were added but it uses more memory and is slower than a Hashtable and so the latter (or it's generic equivalent Dictionary
http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx
Posted Sep 12, 2013, 9:53 AM
VulpesPosted Sep 12, 2013, 9:48 AM
Consequently, when you enumerate the Hashtable, you iterate through the DictionaryEntry instances which is why the control variable of the foreach statement needs to be of that type.
Posted Sep 12, 2013, 9:31 AM
Posted Sep 12, 2013, 9:20 AM