Dictionary#
We used Lists before which can collect many instances of a single type. Sometimes we want to store pairs of information like in a physical dictionary – every word has its meaning stored. So a physical dictionary can be described as a sequence of (string-string) pairs, where the first string is the word that you look up and the second string is the meaning of the word you look up:
var danish2English = new Dictionary<string, string>
{
["kro"] = "inn",
["djævel"] = "devil",
["tåge"] = "fog"
};
// Adding new items
danish2English["demontering"] = "disassembly";
// Reading an item
Console.WriteLine(danish2English["kro"]);
// Iterating
// Each item consists of a *key*-*value* pair.
foreach (var (word, meaning) in danish2English)
Console.WriteLine($"The {word.Length} character word {word} means: {meaning}");
// In a class definition
public class Person
{
public Dictionary<string, int> FoodScore = []; // Do not forget `[]`
}
Activity 38
Based on Activity 36 implement the class Inventory, which has a data field called stock that tracks for each item the amount.
Use a Dictionary to store each item along with its amount.
Lastly, implement the method List<Item> LowStockItems() that returns the items low on stock. You could consider amounts less than five as low for simplicity.
Warning
If you use aggregate datatypes like Dictionary and List in a class definition, do not forget to initialize them using [].