Skip to content

Instantly share code, notes, and snippets.

@arkilis
Created January 2, 2021 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arkilis/5a63272d42e92eb85d43fecda78b7d21 to your computer and use it in GitHub Desktop.
Save arkilis/5a63272d42e92eb85d43fecda78b7d21 to your computer and use it in GitHub Desktop.
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