从字典中获取第一个元素 [英] Get first element from a dictionary
问题描述
我有以下声明:
Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
我需要得到的第一个元素,但是不知道密钥或值。什么是做到这一点的最好方法是什么?
I need to get the first element out, but do not know the key or value. What's the best way to do this?
推荐答案
修改以满足评议。
请注意,要调用首先
这里实际上是调用一个LINQ扩展的IEnumerable的,这是由实施字典< TKEY的,TValue>
。但对于一个字典,第一不具有限定含义。根据这个答案,最后一个项目加最终被第一(换句话说,它的行为就像一个的Stack 的),但是这是特定的实现,它不是的保证的行为。换句话说,要的假设的你会通过调用得到任何定义项的首页的将是乞求的麻烦 - 用它应该被视为类似于获得一个的随机的从字典项,如BOBSON如下所述。但是,有时这是有用的,因为你只需要的从字典中的任何的项目。
Note that to call First
here is actually to call a Linq extension of IEnumerable, which is implemented by Dictionary<TKey,TValue>
. But for a Dictionary, "first" doesn't have a defined meaning. According to this answer, the last item added ends up being the "First" (in other words, it behaves like a Stack), but that is implementation specific, it's not the guaranteed behavior. In other words, to assume you're going to get any defined item by calling First would be to beg for trouble -- using it should be treated as akin to getting a random item from the Dictionary, as noted by Bobson below. However, sometimes this is useful, as you just need any item from the Dictionary.
只需使用LINQ的第一()
:第一个
Just use the Linq First()
:
var first = like.First();
string key = first.Key;
Dictionary<string,string> val = first.Value;
请注意,使用首先
在词典提供您有一个 KeyValuePair </ code>,在这种情况下
KeyValuePair<字符串,字典<字符串,字符串>>
Note that using First
on a dictionary gives you a KeyValuePair
, in this case KeyValuePair<string, Dictionary<string,string>>
.
此外请注意您的 的可能派生从使用的具体含义第一
通过与LINQ的排序依据
组合:
Note also that you could derive a specific meaning from the use of First
by combining it with the Linq OrderBy
:
var first = like.OrderBy(kvp => kvp.Key).First();
这篇关于从字典中获取第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!