从Dictionary< string,string>获取第一个键. [英] Get first key from Dictionary<string, string>
问题描述
我正在使用 System.Collections.Generic.Dictionary< string,string>
.
我想从这本字典中返回第一个键.我尝试了 dic.Keys [0]
,但是我对 Keys
属性(这是一个 KeyCollection
对象)唯一拥有的是枚举器.
I want to return the first key from this dictionary. I tried dic.Keys[0]
but the only thing I have on the Keys
property (which is a KeyCollection
object) is an enumerator.
我是否必须枚举所有键才能得到第一个?
Do I have to enumerate through all the keys to get the first one?
推荐答案
假设您使用的是.NET 3.5:
Assuming you're using .NET 3.5:
dic.Keys.First();
请注意,在字典中没有迭代顺序可以保证键/值对的顺序.您可能会发现,在很多情况下,您会弄出放入字典中的第一把钥匙-但您绝对绝对不能依靠它.正如Skirwan所说,实际上并没有第一"的概念.从本质上讲,以上内容将为您提供词典中的键"-这就是所保证的一切.
Note that there's no guaranteed order in which key/value pairs will be iterated over in a dictionary. You may well find that in lots of cases you get out the first key that you put into the dictionaries - but you absolutely must not rely on that. As Skirwan says, there isn't really a notion of "first". Essentially the above will give you "a key from the dictionary" - that's about all that's guaranteed.
(如果您不知道字典是否为空,则可以使用 FirstOrDefault
.)
(If you don't know whether the dictionary is empty or not, you could use FirstOrDefault
.)
这篇关于从Dictionary< string,string>获取第一个键.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!