Accessing a Dictionary.Keys Key through a numeric index

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

    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 KeyValuePair as the value. The main reasoning for this is that, in general, the Key isn't necessarily directly derivable from the value.

    Then it'd look like this:

    public sealed class CustomDictionary
      : KeyedCollection>
    {
      protected override TKey GetKeyForItem(KeyValuePair item)
      {
        return item.Key;
      }
    }
    

    To use this as in the previous example, you'd do:

    CustomDictionary custDict = new CustomDictionary();
    
    custDict.Add(new KeyValuePair("key", 7));
    
    int valueByIndex = custDict[0].Value;
    int valueByKey = custDict["key"].Value;
    string keyByIndex = custDict[0].Key;
    

提交回复
热议问题