C#:从字典<第一个键,字符串,字符串>

问题描述:

我使用的是 System.Collections.Generic.Dictionary&LT;字符串,字符串方式>

我想返回从这个字典中的第一个关键。我试图 dic.Keys [0] ,但我对属性(唯一这是一个 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.)