Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I rely on the order of a SortedDictionary in Linq, and is it doing this efficiently?
    text
    copied!<p>When using a SortedDictionary in Linq and iterating over the KeyValuePair it provides, can I be assured that a complex linq query will execute it in ascending order? Here's a brief, although a bit confusing example:</p> <pre><code>Random r = new Random(); //build 100 dictionaries and put them into a sorted dictionary //with "priority" as the key and it is a number 0-99. SortedDictionary&lt;int, Dictionary&lt;int, double&gt;&gt; sortedDict = new SortedDictionary&lt;int, Dictionary&lt;int, double&gt;&gt;(); for (int i = 0; i &lt; 100; i++) { Dictionary&lt;int, double&gt; dict = new Dictionary&lt;int, double&gt;(); //create the dictionary and a random 10 k/v pairs for (int j = 0; j &lt; 10; j++) { dict[r.Next(0, 100)] = r.NextDouble() * i * 10; } sortedDict[i] = dict; } IEnumerable&lt;int&gt; keys = Enumerable.Range(0, 100); //the goal is to find the FIRST existence of the "key" inside one //of the inner dictionaries going through the SortedDictionary IN ORDER //this appears to work: var qry = from key in keys from priority in sortedDict where priority.Value.ContainsKey(key) let value = priority.Value[key] group value by key into keyGroup let firstValue = keyGroup.First() select new { Key = keyGroup.Key, Value = firstValue }; // the result is as expected, a list of the numbers at most 0-99 and their // value found in the dictionary with the lowest "priority" </code></pre> <p>The question(s):</p> <ol> <li>It appears to work, but can I rely on this behavior?</li> <li>Is this efficient, or does the group by throw it off?</li> <li>Does adding "sortedDict.Reverse()" work properly too? (it appears to)</li> <li>How would PLinq handle this - and would it still be consistent?</li> </ol> <p>If this isn't guaranteed, I know how I can pull the "priority" into the grouping and order by it after the fact. But I'd rather not...</p>
 

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