Looking values up by key with a dictionary
An array finds a value by its position. A dictionary finds a value by its key, which is often the more natural question.
Key and value
C#
System.Collections.Generic.Dictionary<string, int> stock =
new System.Collections.Generic.Dictionary<string, int>();
stock["bolts"] = 120;
stock["nuts"] = 80;
int bolts = stock["bolts"];What to know before you use one
- Each key appears once. Assigning an existing key replaces its value.
- Asking for a key that is not present throws an exception, so check first when the key is uncertain.
- A dictionary is not ordered in the way a list is, so do not rely on the sequence of its items.
Good fit. Dictionaries suit lookups such as settings by name or a count by product code. For an ordered sequence of items, keep using a list.
Collections are far more useful once you can package behaviour with data, which is the subject of building your own types.