Wörterbuch
Schlüssel und Wert werden hinzugefügt. Der Wert wird zurückgegeben, wenn der Schlüssel eingegeben wird.
Verwendung: Dictionary<KeyClass,ValueClass> dictionary=new Dictionary<KeyClass,ValueClass>();
Beispiel 1:
Lassen Sie uns ein englisch-deutsches Wörterbuch erstellen. Wenn ein englisches Wort geschrieben wird, gibt es ein deutsches Wort zurück.
mainfunc(){
// Let's create an English-German dictionary. Let keys and values be Text.
Dictionary<Text,Text> enDe=new Dictionary<Text,Text>();
// Let's write the words and their equivalents.
enDe.add("Hello","Hallo");
enDe.add("World","Welt");
enDe.add("Language","Sprache");
enDe.add("English","Englisch");
enDe.add("German","Deutsch");
// Let's remove some words.
enDe.remove("English");
enDe.remove("German");
print("Language: {enDe.get("Language")}"); //Language: Sprache
print("Word Count: {enDe.size}"); //Word Count: 3
// Let's print all the English and German words.
print("English Words");
loop(Text key:enDe.keys) print(key);
print("German Words");
loop(Text value:enDe.values) print(value);
print("Dictionary");
loop(Text key:enDe.keys) print("{key}: {enDe.get(key)}");
// Let's reset dictionary.
enDe=new Dictionary<Text,Text>();
print("Word Count: {enDe.size}");
}
Ausgabe:
Language: Sprache
Word Count: 3
English Words
Hello
Language
World
German Words
Hallo
Sprache
Welt
Dictionary
Hello: Hallo
Language: Sprache
World: Welt
Word Count: 0
Beispiel 2:
Lassen Sie uns ein repräsentatives Einkaufssystem erstellen. Lassen Sie uns Produkte hinzufügen und drucken.
mainfunc(){
//When we enter Text, we will get both Text and Int value.
//Let's create a Dictionary by typing Object as Text value as key.
Dictionary<Text,Object> product=new Dictionary<Text,Object>();
// Let's create a List for dictionary.
List<Dictionary<Text,Object>> productList=new List<Dictionary<Text,Object>>();
//Add product info.
product.add("name","Computer");
product.add("description","Fast Computer");
product.add("price",3000);
//Let's add product to list and reset it.
productList.add(product);
product=new Dictionary<Text,Object>();
//Let's add new product info.
product.add("name","Phone");
product.add("description","Smart Phone");
product.add("price",1500);
//Let's add product to list.
productList.add(product);
//Let's print Products List.
print("Products");
loop(Dictionary<Text,Object> _product : productList){
print("Product Name: {_product.get("name")}");
print("Product Description: {_product.get("description")}");
print("Product Price: {_product.get("price")}");
}
}
Ausgabe:
Products
Product Name: Computer
Product Description: Fast Computer
Product Price: 3000
Product Name: Phone
Product Description: Smart Phone
Product Price: 1500