Brij
Brij

Reputation: 13129

Data structure that supports access via index as well as key

Dictionary supports access of elements via a key. List supports access via index. Is there any data structure that supports access via both key and index?

Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("abc", "def");
d.Add("ghi", "ghi");
d.Add("abcd", "abcd");
d.Add("how", "howis");
foreach (KeyValuePair<string, string> kv in d)
   Console.WriteLine(kv.Key);

Output is

abc
ghi 
abcd 
how

So the items come out in the same sequence as they were added. Does that mean dictionary maintains items sequentially ? If yes, can we access them by index ? If no, is there any such collection available which supports accessing elements by index as well as key ?

Upvotes: 1

Views: 1380

Answers (2)

Joe Ratzer
Joe Ratzer

Reputation: 18549

Values in a dictionary are not necessarily unique, hence the key lookup.

The order of elements in a dictionary is non-deterministic, hence the OrderedDictionary.

Upvotes: 1

shahkalpesh
shahkalpesh

Reputation: 33476

I think OrderedDictionary or NameValueCollection is what you are looking for.

Upvotes: 5

Related Questions