How do I get the nth element from a Dictionary?

Viewed 86607
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.

8 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 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;

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>();

d.Add("a", "apple");
d.Add("b", "ball");
d.Add("c", "cat");
d.Add("d", "dog");

int t = 0;
foreach (string s in d.Values)
{
    t++;
    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.

Related