如何从字典中获取第n个元素?

Ada*_*ane 34 c# dictionary

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方法的各种组合.

  • 您可以使用`ElementAt(int)`扩展方法,但是就像thecoop所说的那样,它没有被排序,因此甚至不能保证两次连续调用之间的结果相同. (9认同)

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包含在单个集合类型中.

或者,如果列表非常短,只需通过线性搜索即可通过索引查找...

  • 也许现在5年过去了,我终于可以承认,我纯粹是为了让我的答案看起来比你的得分更好,在公然尝试抢夺时.在我的辩护中,我是新手,也是一个非常刺激的人.所以当投票变老时,也不会让他们纠正他们的方式错误,所以我生活在我的耻辱之中. (6认同)
  • @grenade,我刚刚注意到你真诚的承认内疚!我不知道Jon是否注意到了,但是为了你的荣誉(而不是他*需要*另外10个代表点),我现在已经提出了他的答案,以帮助弥补你的downvote.同时,通过这样做,我现在进一步减少了自己希望得到更多的赞成回答问题而不是Jon Skeet! (3认同)

小智 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)