Reputation:
Is there a way to get a location of a key in a dictionary?
for example, if my keys are 23, 44, 56, 66 and I want the get they key at location 0 it would return me 23. Or key at location 2 would return 56.
Are dictionary keys traversable like this?
Upvotes: 0
Views: 143
Reputation: 3653
From MSDN:
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
So the indices will not be consistent, if ever you did get it.
I suggest you use a List<T>
using something like a KeyValuePair<TKey,TValue>
or a Class, if you can.
Upvotes: 0
Reputation: 833
So yes Dictionary's are able to be iterated through because they are a type of ICollection.
If you really wanted to just find a random key you could just create a random number and use
var randomNumber = 5; (or however you want to get a random number)
var randomKey = yourDictionary.ElementAt(randomNumber).Key;
So this will get the key in the sixth position of the dictionary, and if you wanted you could also get the value by just saying .Value;
Upvotes: 2