Accessing a Dictionary.Keys Key through a numeric index

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

    You could always do this:

    string[] temp = new string[mydict.count];
    mydict.Keys.CopyTo(temp, 0)
    int LastCount = mydict[temp[mydict.count - 1]]
    

    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 on MSDN 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.

提交回复
热议问题