cipher = new Dictionary<char,int>;
cipher.Add( 'a', 324 );
cipher.Add( 'b', 553 );
cipher.Add( 'c', 915 );
如何获得第二元素?例如,我想要类似的东西:
KeyValuePair pair = cipher[1]
一对包含
( 'b', 553 )
根据合作社使用List的建议,一切正常:
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 ];
假设我对这些项目按添加的顺序保留在列表中是正确的,我相信我可以只使用
List
而不是建议的SortedList
。 最佳答案
问题是字典未排序。您需要的是SortedList,它允许您通过索引和键来获取值,尽管您可能需要在构造函数中指定自己的比较器才能获得所需的排序。然后,您可以访问键和值的有序列表,并根据需要使用IndexOfKey/IndexOfValue方法的各种组合。
关于c# - 如何从字典中获取第n个元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1172931/