Accessing a Dictionary.Keys Key through a numeric index

前端 未结 15 1222
失恋的感觉
失恋的感觉 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:02

    One alternative would be a KeyedCollection if the key is embedded in the value.

    Just create a basic implementation in a sealed class to use.

    So to replace Dictionary (which isn't a very good example as there isn't a clear key for a int).

    private sealed class IntDictionary : KeyedCollection
    {
        protected override string GetKeyForItem(int item)
        {
            // The example works better when the value contains the key. It falls down a bit for a dictionary of ints.
            return item.ToString();
        }
    }
    
    KeyedCollection intCollection = new ClassThatContainsSealedImplementation.IntDictionary();
    
    intCollection.Add(7);
    
    int valueByIndex = intCollection[0];
    

提交回复
热议问题