Generic Dictionaries and Indexes

E

Ethan Strauss

Hi,
I have been using a variety of generic collections and I really like
them, but I have just noticed something weird ...

If you have a generic Dictionary (or SortedList), you can retrieve elements
from the list by index (I think).
So:
Dictionary<string, string> ThisStringDictionary = new Dictionary<string,
string>();
---Code to populate dictionary---
string ThisValue = ThisStringDictionary[0]; //This should get you the
value of the first element of the dictionary and throw no errors. Right?


I have a SortedList which is defined as
SortedList <string, MyCustomType> MySortedList = new SortedList
<string, MyCustomType>();
but, the fact is that almost all of the keys are, in fact integers being
treated as strings.

So I have situations where I have something like :
SortedList <string, MyCustomType> MySortedList = new SortedList
<string, MyCustomType>();
---Code to populate MySortedList ---
but now
MySortedList [0] != MySortedList ["0"];

This is all OK, the computer differentiates the two just fine.

My real question is what if I have a SortedList <int, anyType>? How can it
tell if I am asking for an element by index or by key?
I am guessing that the fact that I have this questions means I am missing
something. Can anyone fill me in?
Thanks!
Ethan

Ethan Strauss Ph.D.
Bioinformatics Scientist
Promega Corporation
2800 Woods Hollow Rd.
Madison, WI 53711
608-274-4330
800-356-9526
(e-mail address removed)
 
S

sdbillsfan

So:
Dictionary<string, string> ThisStringDictionary = new Dictionary<string,
string>();
---Code to populate dictionary---
string ThisValue = ThisStringDictionary[0]; //This should get you the
value of the first element of the dictionary and throw no errors. Right?

If you had taken 10 seconds to verify this using the documentation you
could have saved yourself the trouble of writing this post and us the
trouble of reading it :)
 
J

Jon Skeet [C# MVP]

I have been using a variety of generic collections and I really like
them, but I have just noticed something weird ...

If you have a generic Dictionary (or SortedList), you can retrieve elements
from the list by index (I think).

Dictionary? No. There *is* no index as such.

SortedList? Yes - but only via the Values property (which implements
IList<TKey>).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top