Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System.Collections.Generic;
// example of string key and value is string
Dictionary<string, string> openWith = new Dictionary<string, string>();
// example of int key and value is a list
Dictionary<int, string[]> OtherType = new Dictionary<int, string[]>();
// add elements
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
// update existing element, if key not exists, a new element will be created
openWith["txt"] = "winword.exe2";
// get values from dictionary 1
string iVal;
if(openWith.TryGetValue("ext", out iVal)) {
// key ext exists
} else {
// key ext not exists
}
// get values from dictionary 2
if(openWith.ContainsKey("ext")) {
// key ext exists
} else {
// key ext not exists
}
// dictionary with init values
var dict = new Dictionary<int, string>() {
[1] = "BMW",
[2] = "Audi",
[3] = "Lexus"
}
foreach (var key in dict.Keys) {
Console.WriteLine($"{key} - dict[key]");
}
// get all the keys
oreach (string key in dict.Keys) {
Console.WriteLine("Key = {0}", key);
}
// get all the values
foreach (string value in dict.Values){
Console.WriteLine("value = {0}", value);
}
// add new element
try {
dict.Add(4, "Honda");
} catch (ArgumentException) {
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
// delete an element
if (dict.ContainsKey("doc")) {
dict.Remove("doc");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment