如何从词典中获取第n个元素? [英] How do I get the nth element from a Dictionary?

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

问题描述

cipher = new Dictionary<char,int>;
cipher.Add( 'a', 324 );
cipher.Add( 'b', 553 );
cipher.Add( 'c', 915 );

如何获得第二个元素?例如,我想要的是:

How to get the 2nd element? For example, I'd like something like:

KeyValuePair pair = cipher[1]

对包含('b',553)

根据使用列表的合作伙伴建议,事情正在发挥作用:

Based on the coop's suggestion using a List, things are working:

List<KeyValuePair<char, int>> cipher = new List<KeyValuePair<char, int>>();
cipher.Add( new KeyValuePair<char, int>( 'a', 324 ) );
cipher.Add( new KeyValuePair<char, int>( 'b', 553 ) );
cipher.Add( new KeyValuePair<char, int>( 'c', 915 ) );

KeyValuePair<char, int> pair = cipher[ 1 ];

假设我是正确的,项目按照添加的顺序留在列表中,我相信根据建议,我可以使用列表而不是 SortedList

Assuming that I'm correct that the items stay in the list in the order they are added, I believe that I can just use a List as opposed to a SortedList as suggested.

推荐答案

问题是字典没有排序。您想要的是 SortedList ,它允许您通过索引获取值以及关键,虽然您可能需要在构造函数中指定自己的比较器来获取所需的排序。然后,您可以访问按键和值的有序列表,并根据需要使用IndexOfKey / IndexOfValue方法的各种组合。

The problem is a Dictionary isn't sorted. What you want is a SortedList, which allows you to get values by index as well as key, although you may need to specify your own comparer in the constructor to get the sorting you want. You can then access an ordered list of the Keys and Values, and use various combinations of the IndexOfKey/IndexOfValue methods as needed.

这篇关于如何从词典中获取第n个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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