Accessing a Dictionary.Keys Key through a numeric index

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

    A dictionary may not be very intuitive for using index for reference but, you can have similar operations with an array of KeyValuePair:

    ex. KeyValuePair<string, string>[] filters;

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

    As @Falanwe points out in a comment, doing something like this is incorrect:

    int LastCount = mydict.Keys.ElementAt(mydict.Count -1);
    

    You should not depend on the order of keys in a Dictionary. If you need ordering, you should use an OrderedDictionary, as suggested in this answer. The other answers on this page are interesting as well.

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

    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.

    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.

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