通过数字索引访问Dictionary.Keys键 [英] Accessing a Dictionary.Keys Key through a numeric index

查看:103
本文介绍了通过数字索引访问Dictionary.Keys键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用字典< string,int> 其中 int 是密钥的计数。

I'm using a Dictionary<string, int> where the int is a count of the key.

现在,我需要访问Dictionary中的最后插入的Key,但是我不知道它的名字。明显的尝试:

Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:

int LastCount = mydict[mydict.keys[mydict.keys.Count]];

不工作,因为 Dictionary.Keys 不实现[] -indexer。

does not work, because Dictionary.Keys does not implement a []-indexer.

我只是想知道是否有类似的类?我想到使用一个Stack,但只存储一个字符串。我现在可以创建自己的结构,然后使用一个 Stack< MyStruct> ,但是我想知道是否有另一个替代方法,本质上是一个Dictionary,它实现一个[钥匙?

I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?

推荐答案

正如@Falanwe在评论中指出的,做这样的事情是 不正确

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

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

不应该取决于字典中键的顺序。如果您需要订购,您应该使用 OrderedDictionary ,如此答案所建议的。此页面上的其他答案也很有意思。

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.

这篇关于通过数字索引访问Dictionary.Keys键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆