从字典中获取第一个元素 [英] Get first element from a dictionary

查看:52
本文介绍了从字典中获取第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下声明:

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?

推荐答案

注意这里调用First其实就是调用了IEnumerable的一个Linq扩展,由Dictionary.但是对于字典,第一"没有明确的含义.根据这个答案,添加的最后一项最终成为第一"(换句话说,它的行为类似于 Stack),但这是特定于实现的,它不是保证行为.换句话说,要假设您将通过调用 First 来获得任何定义的项目,那就是自找麻烦——使用它应该被视为类似于获得一个随机 字典中的项目,如下面的 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 First():

Just use the Linq First():

var first = like.First();
string key = first.Key;
Dictionary<string,string> val = first.Value;

注意,在字典上使用 First 会给你一个 KeyValuePair,在这种情况下 KeyValuePair>.

Note that using First on a dictionary gives you a KeyValuePair, in this case KeyValuePair<string, Dictionary<string,string>>.

另请注意,您可以通过将 First 与 Linq OrderBy 结合使用,从而获得特定含义:

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屋!

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