我如何从一个字典的第n个元素? [英] How do I get the nth element from a Dictionary?

查看:1802
本文介绍了我如何从一个字典的第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 ];

假设我是正确的,因为项目留在它们被添加的顺序列表中,我相信,我可以只使用一个列表而不是一个排序列表的建议。

推荐答案

问题是一个字典是没有排序。你想要的是一个排序列表,它允许您通过索引获取值以及键,虽然你可能需要指定在构造自己的比较器,以获得您想要的排序。然后,您可以访问项和值的有序列表,并根据需要使用的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天全站免登陆