Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the nth element from a Dictionary?

Tags:

c#

dictionary

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] 

Where pair contains ( '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 ]; 

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.

like image 937
Adam Kane Avatar asked Jul 23 '09 16:07

Adam Kane


People also ask

How to get the nth element in a dictionary?

If using a sorted list, a much easier way is to just use Cipher. GetKey(n) for the nth key and Cipher. GetByIndex(n) for the nth value.

How do you find the last element of a dictionary?

var last = dictionary. Values. Last();


2 Answers

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.

like image 169
thecoop Avatar answered Sep 23 '22 18:09

thecoop


like this:

int n = 0; int nthValue = cipher[cipher.Keys.ToList()[n]]; 

note that you will also need a reference to Linq at the top of your page...

using System.Linq; 
like image 21
grenade Avatar answered Sep 21 '22 18:09

grenade