cipher = new Dictionary<char,int>;
cipher.Add( 'a', 324 );
cipher.Add( 'b', 553 );
cipher.Add( 'c', 915 );
Run Code Online (Sandbox Code Playgroud)
如何获得第二个元素?例如,我想要像:
KeyValuePair pair = cipher[1]
Run Code Online (Sandbox Code Playgroud)
哪一对包含 ( '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 ];
Run Code Online (Sandbox Code Playgroud)
假设我是正确的,项目按照添加的顺序保留在列表中,我相信我可以使用a List
而不是SortedList
建议的.
the*_*oop 34
问题是字典没有排序.你想要的是一个SortedList,它允许你通过索引和键来获取值,尽管你可能需要在构造函数中指定你自己的比较器来获得你想要的排序.然后,您可以访问Keys和Values的有序列表,并根据需要使用IndexOfKey/IndexOfValue方法的各种组合.
gre*_*ade 28
像这样:
int n = 0;
int nthValue = cipher[cipher.Keys.ToList()[n]];
Run Code Online (Sandbox Code Playgroud)
请注意,您还需要在页面顶部引用Linq ...
using System.Linq;
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 17
你真的需要通过钥匙查找吗?如果没有,请使用List<KeyValuePair<char, int>>
(或者更好的是,创建一个类型来封装char和int).
字典并非固有排序-该词典的实现是在.NET排序由键排序,而不是插入顺序.
如果您需要通过插入顺序和键访问集合,我建议将List和Dictionary包含在单个集合类型中.
或者,如果列表非常短,只需通过线性搜索即可通过索引查找...
小智 6
你可以ElementAt()
像这样使用:
cipher.ElementAt(index);
Run Code Online (Sandbox Code Playgroud)
它比Select
选项更好,因为这样你不必遍历字典:
/// <summary>Returns the element at a specified index in a sequence.</summary>
/// <returns>The element at the specified position in the source sequence.</returns>
/// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> to return an element from.</param>
/// <param name="index">The zero-based index of the element to retrieve.</param>
/// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="source" /> is null.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> is less than 0 or greater than or equal to the number of elements in <paramref name="source" />.</exception>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
73275 次 |
最近记录: |