Accessing a Dictionary.Keys Key through a numeric index

前端 未结 15 1178
失恋的感觉
失恋的感觉 2020-12-07 13:49

I\'m using a Dictionary where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dict

相关标签:
15条回答
  • 2020-12-07 14:10

    You can use an OrderedDictionary.

    Represents a collection of key/value pairs that are accessible by the key or index.

    0 讨论(0)
  • 2020-12-07 14:10

    A Dictionary is a Hash Table, so you have no idea the order of insertion!

    If you want to know the last inserted key I would suggest extending the Dictionary to include a LastKeyInserted value.

    E.g.:

    public MyDictionary<K, T> : IDictionary<K, T>
    {
        private IDictionary<K, T> _InnerDictionary;
    
        public K LastInsertedKey { get; set; }
    
        public MyDictionary()
        {
            _InnerDictionary = new Dictionary<K, T>();
        }
    
        #region Implementation of IDictionary
    
        public void Add(KeyValuePair<K, T> item)
        {
            _InnerDictionary.Add(item);
            LastInsertedKey = item.Key;
    
        }
    
        public void Add(K key, T value)
        {
            _InnerDictionary.Add(key, value);
            LastInsertedKey = key;
        }
    
        .... rest of IDictionary methods
    
        #endregion
    
    }
    

    You will run into problems however when you use .Remove() so to overcome this you will have to keep an ordered list of the keys inserted.

    0 讨论(0)
  • 2020-12-07 14:10

    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: SortedList Class , SortedList Generic Class .

    0 讨论(0)
  • 2020-12-07 14:11

    Visual Studio's UserVoice gives a link to generic OrderedDictionary implementation by dotmore.

    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:

    class ListArray<T> : List<T[]> { }
    

    You may also declare it with constructors:

    class ListArray<T> : List<T[]>
    {
        public ListArray() : base() { }
        public ListArray(int capacity) : base(capacity) { }
    }
    

    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:

    ListArray<string> settingsRead = new ListArray<string>();
    using (var sr = new StreamReader(myFile))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            string[] keyValueStrings = line.Split(separator);
            for (int i = 0; i < keyValueStrings.Length; i++)
                keyValueStrings[i] = keyValueStrings[i].Trim();
            settingsRead.Add(keyValueStrings);
        }
    }
    // Later you get your key/value strings simply by index
    string[] myKeyValueStrings = settingsRead[index];
    

    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.

    0 讨论(0)
  • 2020-12-07 14:15

    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?

    If that's correct, is there any reason you can't instead use Dictionary<int, string> so that you can use mydict[ mydict.Keys.Count ]?

    0 讨论(0)
  • 2020-12-07 14:20

    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.

    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).

    0 讨论(0)
提交回复
热议问题