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
where pair contains ( 'b', 553 )
Based on thecoop's suggestion using a List, things are workking:
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 that they are added, I belive that I can just use a List as opposed to a SortedList as suggested.
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.
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...
Do you actually need to look up by the key? If not, use a
List<KeyValuePair<char, int>> (or better yet, create a type to encapsulate the char and the int).
Dictionaries aren't inherently sorted - the dictionary implementations which are sorted in .NET are sorted by key, not by insertion order.
If you need to access the collection by both insertion order and key, I'd recommend encapsulating a List and a Dictionary in a single collection type.
Alternatively, if the list is going to be quite short, allow lookup by index just by doing a linear search...
Just to cling to your original spec for a Dictionary, I slung some code and came up with:
Dictionary<string, string> d = new Dictionary<string, string>();
int t = 0;
foreach (string s in d.Values)
if (t == 2) Console.WriteLine(s);
and it does seem to write the second item ("ball") to the console repeatably. If you wrapped it into a method call to get the nth element, it would probably work. This is pretty ugly, though. If you could do a SortedList instead, as @thecoop suggests, you'd be better off.
There was a dupe of this question asked here: How to retrieve Nth item in dictionary?. It should be closed soon, but I noticed that the answers here are missing the new OrderedDictionary class.
There is now (as of .NET 4), an OrderedDictionary class. This allows fast lookups while providing ordering. The Item(Int32) method returns the nth element.
Do NOT try this: This was a dumb idea - sorry guys!
'cause the 2ND element is index 1!