Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I know this question is too old to get any upvotes, but I didn't like any of the answers so will post my own in the hopes of offering another option to future readers.</p> <p>The following <em>did not</em> work for me on .NET 4.0:</p> <pre><code>myDictionary.Values.OrderBy( x =&gt; x.Key ).Last(); </code></pre> <p>I suspect the problem is that the 'x' represents a value in the dictionary, and a value has no key (the dictionary stores the key, the dictionary values do not). I may also be making a mistake in my usage of the technique.</p> <p>Either way, this solution would be slow for large dictionaries, probably <em>O(n log n)</em> for CS folks, because it is <strong>sorting the entire dictionary</strong> just to get one entry. That's like rearranging your entire DVD collection just to find one specific movie.</p> <hr> <pre><code>var lastDicVal = dic.Values.Last(); </code></pre> <p>is well established as a bad idea. In practice, this solution does actually work most of the time due to Microsoft's implementation of the dictionary, but in software engineering terms that is meaningless and should not be relied upon. Even if it works every time for the rest of eternity, it represents a sloppy, unsafe coding practice.</p> <hr> <p>My solution is as follows:</p> <pre><code>var lastValue = dic[dic.Keys.Max()]; </code></pre> <p>The Keys.max() function is much faster than sorting <em>O(n)</em> instead of <em>O(n log n)</em>. If performance is important enough that even <em>O(n)</em> is too slow, the last inserted key can be tracked in a separate variable used to replace <em>dic.Keys.Max()</em>, which will make the entire lookup O(1) plus whatever overhead exists in tracking the last inserted entry.</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