How to enumerate through Dictionary
How can I retreive elemenents in Dictionary开发者_开发知识库 through index (int index )..;Instead of a key
foreach(KeyValuePair<String,String> pair in dictionary)
{
string key = pair.Key;
string value = pair.Value;
}
or to get access by item
dictionary.ToList()[index].Key/Value :-)
Dictionary is an unordered collection so it does not provide random access. Only types that implement IList<T>
provide random access to their contents.
Well, that's not totally correct - you could use a OrderedDictionary
(which would give you random access without IList<T>
) but you lose the benefits of the generic dictionary. If you need random access, most likely you shouldn't be using a Dictionary.
check out following
Accessing a Dictionary.Keys Key through a numeric index
There is no method for retrieving elements by index because the Dictionary class does not specify the order in which key/value pairs are stored. If you need both key and index lookup use the OrderedDictionary class.
I found this useful:
foreach (var key in dictionary.Keys)
{
var value = dictionary[key];
}
or
foreach (var value in dictionary.Values)
{
// use value
}
精彩评论