Note that there are some explanatory texts on larger screens.

plurals
  1. POSort a .NET Dictionary - bug or unsupported feature?
    text
    copied!<p>I recently found productive code including the sorting of a .NET <code>Dictionary&lt;string,CustomObject&gt;</code>. It was basically to copy the dictionary to a temporary one, then .Clear() the original and insert the KeyValuePairs ordered through a Linq expression, by a DateTime value in the CustomObjects.</p> <p>I expected this code not to work and was already removing it, expecting that a dictionary (as well as a HashSet) can't be sorted. Then I wrote the following test code, which, to my surprise, showed a sorted output from the dictionary, when iterated with a foreach loop.</p> <p>Is this a random effect in the current implementation of <code>Dictionary&lt;TKey, TValue&gt;</code>, which may work in the current case, but fail in another implementation of .NET? Or is it a standard feature to be used in .NET Dictionaries?</p> <p>I still consider the productive code to be faulty, but working. Should I remove it, requiring a long testing, if the order is used somewhere else than in the place where I found the sorting routine, or is it safe to leave it as it is?</p> <p>Here's my test code:</p> <pre><code>static void Main(string[] args) { var rnd = new Random(); var dict = new Dictionary&lt;int, string&gt;(); for (int i = 0 ; i &lt; 10 ; i++) { int rndValue; do { rndValue = rnd.Next(100); } while (dict.ContainsKey(rndValue)); dict.Add(rndValue, "MyValue#" + i); } foreach (KeyValuePair&lt;int, string&gt; pair in dict) { Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value); } Console.Write("Enter..."); Console.ReadLine(); var dictBuff = dict.ToDictionary(p =&gt; p.Key, p =&gt; p.Value); dict.Clear(); var sortdict = from pair in dictBuff orderby pair.Key ascending select pair; foreach (KeyValuePair&lt;int, string&gt; pair in sortdict) { dict.Add(pair.Key, pair.Value); } Console.WriteLine("'Sorted' Dictionary:"); foreach (KeyValuePair&lt;int, string&gt; pair in dict) { Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value); } Console.Write("Enter..."); Console.ReadLine(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload