<p>I'm using a <code>Dictionary&lt;string, int&gt;</code> where the <code>int</code> is a count of the key.</p>

<p>Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:</p>

<pre><code>int LastCount = mydict[mydict.keys[mydict.keys.Count]];
</code></pre>

<p>does not work, because <code>Dictionary.Keys</code> does not implement a []-indexer.</p>

<p>I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a <code>Stack&lt;MyStruct&gt;</code>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?</p>

[{'answer_id': 4252, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 3, 'selected': False, 'text': '<p>You could always do this:</p>\n\n<pre><code>string[] temp = new string[mydict.count];\nmydict.Keys.CopyTo(temp, 0)\nint LastCount = mydict[temp[mydict.count - 1]]\n</code></pre>\n\n<p>But I wouldn\'t recommend it. There\'s no guarantee that the last inserted key will be at the end of the array. The ordering for Keys <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys" rel="nofollow noreferrer">on MSDN</a> is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you\'d be better off building in proper bookkeeping like a stack--as you suggest (though I don\'t see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.</p>\n'}, {'answer_id': 4255, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 2, 'selected': False, 'text': "<p>I don't know if this would work because I'm pretty sure that the keys aren't stored in the order they are added, but you could cast the KeysCollection to a List and then get the last key in the list... but it would be worth having a look.</p>\n\n<p>The only other thing I can think of is to store the keys in a lookup list and add the keys to the list before you add them to the dictionary... it's not pretty tho.</p>\n"}, {'answer_id': 4258, 'author': 'Juan', 'author_id': 550, 'author_profile': 'https://Stackoverflow.com/users/550', 'pm_score': 3, 'selected': False, 'text': '<p>I think you can do something like this, the syntax might be wrong, havent used C# in a while\nTo get the last item</p>\n\n<pre><code>Dictionary&lt;string, int&gt;.KeyCollection keys = mydict.keys;\nstring lastKey = keys.Last();\n</code></pre>\n\n<p>or use Max instead of Last to get the max value, I dont know which one fits your code better.</p>\n'}, {'answer_id': 4315, 'author': 'Stephen Pellicer', 'author_id': 360, 'author_profile': 'https://Stackoverflow.com/users/360', 'pm_score': 2, 'selected': False, 'text': "<p>I agree with the second part of Patrick's answer. Even if in some tests it seems to keep insertion order, the documentation (and normal behavior for dictionaries and hashes) explicitly states the ordering is unspecified.</p>\n\n<p>You're just asking for trouble depending on the ordering of the keys. Add your own bookkeeping (as Patrick said, just a single variable for the last added key) to be sure. Also, don't be tempted by all the methods such as Last and Max on the dictionary as those are probably in relation to the key comparator (I'm not sure about that).</p>\n"}, {'answer_id': 4319, 'author': 'Jeremy Privett', 'author_id': 560, 'author_profile': 'https://Stackoverflow.com/users/560', 'pm_score': 2, 'selected': False, 'text': '<p>The way you worded the question leads me to believe that the int in the Dictionary contains the item\'s "position" on the Dictionary. Judging from the assertion that the keys aren\'t stored in the order that they\'re added, if this is correct, that would mean that keys.Count (or .Count - 1, if you\'re using zero-based) should still always be the number of the last-entered key?</p>\n\n<p>If that\'s correct, is there any reason you can\'t instead use Dictionary&lt;int, string&gt; so that you can use mydict[ mydict.Keys.Count ]?</p>\n'}, {'answer_id': 4589, 'author': 'Calanus', 'author_id': 445, 'author_profile': 'https://Stackoverflow.com/users/445', 'pm_score': 3, 'selected': False, 'text': "<p>Why don't you just extend the dictionary class to add in a last key inserted property. Something like the following maybe?</p>\n\n<pre><code>public class ExtendedDictionary : Dictionary&lt;string, int&gt;\n{\n    private int lastKeyInserted = -1;\n\n    public int LastKeyInserted\n    {\n        get { return lastKeyInserted; }\n        set { lastKeyInserted = value; }\n    }\n\n    public void AddNew(string s, int i)\n    {\n        lastKeyInserted = i;\n\n        base.Add(s, i);\n    }\n}\n</code></pre>\n"}, {'answer_id': 5540, 'author': 'Andrew Peters', 'author_id': 608, 'author_profile': 'https://Stackoverflow.com/users/608', 'pm_score': 6, 'selected': False, 'text': '<p>You can use an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary" rel="nofollow noreferrer">OrderedDictionary</a>.</p>\n\n<blockquote>\n  <p>Represents a collection of key/value\n  pairs that are accessible by the key\n  or index.</p>\n</blockquote>\n'}, {'answer_id': 756286, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>A Dictionary is a Hash Table, so you have no idea the order of insertion!</p>\n\n<p>If you want to know the last inserted key I would suggest extending the Dictionary to include a LastKeyInserted value.</p>\n\n<p>E.g.:</p>\n\n<pre><code>public MyDictionary&lt;K, T&gt; : IDictionary&lt;K, T&gt;\n{\n    private IDictionary&lt;K, T&gt; _InnerDictionary;\n\n    public K LastInsertedKey { get; set; }\n\n    public MyDictionary()\n    {\n        _InnerDictionary = new Dictionary&lt;K, T&gt;();\n    }\n\n    #region Implementation of IDictionary\n\n    public void Add(KeyValuePair&lt;K, T&gt; item)\n    {\n        _InnerDictionary.Add(item);\n        LastInsertedKey = item.Key;\n\n    }\n\n    public void Add(K key, T value)\n    {\n        _InnerDictionary.Add(key, value);\n        LastInsertedKey = key;\n    }\n\n    .... rest of IDictionary methods\n\n    #endregion\n\n}\n</code></pre>\n\n<p>You will run into problems however when you use <code>.Remove()</code> so to overcome this you will have to keep an ordered list of the keys inserted.</p>\n'}, {'answer_id': 2619931, 'author': 'Glenn Slayden', 'author_id': 147511, 'author_profile': 'https://Stackoverflow.com/users/147511', 'pm_score': 2, 'selected': False, 'text': '<p>In case you decide to use dangerous code that is subject to breakage, this extension function will fetch a key from a <code>Dictionary&lt;K,V&gt;</code> according to its internal indexing (which for Mono and .NET currently appears to be in the same order as you get by enumerating the <code>Keys</code> property).</p>\n\n<p>It is much preferable to use Linq:  <code>dict.Keys.ElementAt(i)</code>, but that function will iterate O(N); the following is O(1) but with a reflection performance penalty.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\npublic static class Extensions\n{\n    public static TKey KeyByIndex&lt;TKey,TValue&gt;(this Dictionary&lt;TKey, TValue&gt; dict, int idx)\n    {\n        Type type = typeof(Dictionary&lt;TKey, TValue&gt;);\n        FieldInfo info = type.GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance);\n        if (info != null)\n        {\n            // .NET\n            Object element = ((Array)info.GetValue(dict)).GetValue(idx);\n            return (TKey)element.GetType().GetField("key", BindingFlags.Public | BindingFlags.Instance).GetValue(element);\n        }\n        // Mono:\n        info = type.GetField("keySlots", BindingFlags.NonPublic | BindingFlags.Instance);\n        return (TKey)((Array)info.GetValue(dict)).GetValue(idx);\n    }\n};\n</code></pre>\n'}, {'answer_id': 4735712, 'author': 'Vitor Hugo', 'author_id': 581486, 'author_profile': 'https://Stackoverflow.com/users/581486', 'pm_score': 9, 'selected': True, 'text': '<p>As @Falanwe points out in a comment, doing something like this is <strong><em>incorrect</em></strong>:</p>\n\n<pre><code>int LastCount = mydict.Keys.ElementAt(mydict.Count -1);\n</code></pre>\n\n<p>You <strong>should not</strong> depend on the order of keys in a Dictionary. If you need ordering, you should use an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary" rel="noreferrer">OrderedDictionary</a>, as suggested in this <a href="https://stackoverflow.com/a/5540/1724702">answer</a>. The other answers on this page are interesting as well.</p>\n'}, {'answer_id': 6755798, 'author': 'Daniel Ballinger', 'author_id': 54026, 'author_profile': 'https://Stackoverflow.com/users/54026', 'pm_score': 2, 'selected': False, 'text': '<p>One alternative would be a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.keyedcollection-2" rel="nofollow noreferrer">KeyedCollection</a> if the key is embedded in the value.</p>\n\n<p>Just create a basic implementation in a sealed class to use.</p>\n\n<p>So to replace <code>Dictionary&lt;string, int&gt;</code> (which isn\'t a very good example as there isn\'t a clear key for a int).</p>\n\n<pre><code>private sealed class IntDictionary : KeyedCollection&lt;string, int&gt;\n{\n    protected override string GetKeyForItem(int item)\n    {\n        // The example works better when the value contains the key. It falls down a bit for a dictionary of ints.\n        return item.ToString();\n    }\n}\n\nKeyedCollection&lt;string, int&gt; intCollection = new ClassThatContainsSealedImplementation.IntDictionary();\n\nintCollection.Add(7);\n\nint valueByIndex = intCollection[0];\n</code></pre>\n'}, {'answer_id': 6759645, 'author': 'takrl', 'author_id': 520044, 'author_profile': 'https://Stackoverflow.com/users/520044', 'pm_score': 2, 'selected': False, 'text': '<p>To expand on Daniels post and his comments regarding the key, since the key is embedded within the value anyway, you could resort to using a <code>KeyValuePair&lt;TKey, TValue&gt;</code> as the value. The main reasoning for this is that, in general, the Key isn\'t necessarily directly derivable from the value.</p>\n\n<p>Then it\'d look like this:</p>\n\n<pre><code>public sealed class CustomDictionary&lt;TKey, TValue&gt;\n  : KeyedCollection&lt;TKey, KeyValuePair&lt;TKey, TValue&gt;&gt;\n{\n  protected override TKey GetKeyForItem(KeyValuePair&lt;TKey, TValue&gt; item)\n  {\n    return item.Key;\n  }\n}\n</code></pre>\n\n<p>To use this as in the previous example, you\'d do:</p>\n\n<pre><code>CustomDictionary&lt;string, int&gt; custDict = new CustomDictionary&lt;string, int&gt;();\n\ncustDict.Add(new KeyValuePair&lt;string, int&gt;("key", 7));\n\nint valueByIndex = custDict[0].Value;\nint valueByKey = custDict["key"].Value;\nstring keyByIndex = custDict[0].Key;\n</code></pre>\n'}, {'answer_id': 29263349, 'author': 'Sharunas Bielskis', 'author_id': 4403269, 'author_profile': 'https://Stackoverflow.com/users/4403269', 'pm_score': 2, 'selected': False, 'text': '<p>You can also use SortedList and its Generic counterpart. These two classes and in Andrew Peters answer mentioned OrderedDictionary are dictionary classes in which items can be accessed by index (position) as well as by key. How to use these classes you can find: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.sortedlist" rel="nofollow noreferrer">SortedList Class</a> , <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2" rel="nofollow noreferrer">SortedList Generic Class</a> .</p>\n'}, {'answer_id': 36462499, 'author': 'espaciomore', 'author_id': 2743497, 'author_profile': 'https://Stackoverflow.com/users/2743497', 'pm_score': 2, 'selected': False, 'text': '<p>A dictionary may not be very intuitive for using index for reference but, you can have similar operations with an array of <strong>KeyValuePair</strong>:</p>\n\n<p>ex.\n<code>KeyValuePair&lt;string, string&gt;[] filters;</code></p>\n'}, {'answer_id': 40397023, 'author': 'quicktrick', 'author_id': 6123485, 'author_profile': 'https://Stackoverflow.com/users/6123485', 'pm_score': 1, 'selected': False, 'text': '<p>Visual Studio\'s <a href="https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/16494583-generic-ordereddictionary" rel="nofollow noreferrer">UserVoice</a> gives a link to <a href="https://github.com/mattmc3/dotmore/blob/master/dotmore/Collections/Generic/OrderedDictionary.cs" rel="nofollow noreferrer">generic OrderedDictionary implementation</a> by dotmore.</p>\n\n<p>But if you only need to get key/value pairs by index and don\'t need to get values by keys, you may use one simple trick. Declare some generic class (I called it ListArray) as follows:</p>\n\n<pre><code>class ListArray&lt;T&gt; : List&lt;T[]&gt; { }\n</code></pre>\n\n<p>You may also declare it with constructors:</p>\n\n<pre><code>class ListArray&lt;T&gt; : List&lt;T[]&gt;\n{\n    public ListArray() : base() { }\n    public ListArray(int capacity) : base(capacity) { }\n}\n</code></pre>\n\n<p>For example, you read some key/value pairs from a file and just want to store them in the order they were read so to get them later by index:</p>\n\n<pre><code>ListArray&lt;string&gt; settingsRead = new ListArray&lt;string&gt;();\nusing (var sr = new StreamReader(myFile))\n{\n    string line;\n    while ((line = sr.ReadLine()) != null)\n    {\n        string[] keyValueStrings = line.Split(separator);\n        for (int i = 0; i &lt; keyValueStrings.Length; i++)\n            keyValueStrings[i] = keyValueStrings[i].Trim();\n        settingsRead.Add(keyValueStrings);\n    }\n}\n// Later you get your key/value strings simply by index\nstring[] myKeyValueStrings = settingsRead[index];\n</code></pre>\n\n<p>As you may have noticed, you can have not necessarily just pairs of key/value in your ListArray. The item arrays may be of any length, like in jagged array.</p>\n'}]
['https://Stackoverflow.com/questions/4227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91/']