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.
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.
var last = dictionary. Values. Last();
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 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With