Normally, I use a dictionary like a list, but with a key of a different type. I like the ability to quickly access individual items in the dictionary without having to loop through it until I find the item with the right property (because the property I'm looking for is in the Key).
But there is another possible use of a dictionary. I could just use the Key to store property A and the Value to store property B without ever using the dictionary's special functionality. For example, I could store a list of persons just by storing the forename in the key and the family name in the value (let's assume, for the sake of simplicity, that there won't ever be two people with the same forename, because I just couldn't come up with an better example). I would only use that dictionary to loop through it in a foreach loop and add items to it (no removing, sorting or accessing individual items). There would actually be no difference to using a List<KeyValuePair<string, string>>
from using a Dictionary<string, string>
(at least not in the example that I gave - I know that I could e. g. store multiple items wiht the same key in the list).
So, to sum it up, what should I do when I don't need to use the special functionalities a dictionary provides and just use it to store something that has exactly two properties:
- use a
Dictionary<,>
- use a
List<KeyValuePair<,>
- use a
List<MyType>
withMyType
being a custom class that contains the two properties and a constructor.
List<KeyValuePair<string, string>>
but its name is too long so most of the people useDictionary<string,string>
here, orStringDictionary
what is even shorter.List<Tuple<string,string>>
.List<KeyValuePair<string, string>>
but its name is too long so most of the people useDictionary<string,string>
Ridiculous. That's not why people useDictionary
. It is an map data structure. When you need to access an element with a key efficiently O(1)Dictionary
is used, not becauseList<KeyValuePair<string, string>>
is big. and alsoList<Tuple<string,string>>
is not a best fit. When you're reading a code which usesTuple
, how sure you're that what is inside theTuple
?