C#:从字典&LT第一个键,字符串,字符串> [英] C#: get first key from Dictionary<string, string>

查看:60
本文介绍了C#:从字典&LT第一个键,字符串,字符串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想返回从这个字典中的第一个关键。我试图 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.)

这篇关于C#:从字典&LT第一个键,字符串,字符串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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