How to create and use Dictionary in Unity using C#

· 1 min read

Like many other languages, C# does have the dictionary data type:

Features of Dictionary in C#:

  • Not sorted
  • Key-value pair
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");
}