-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdictionary-vs-map.cs
50 lines (40 loc) · 1.13 KB
/
dictionary-vs-map.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// C# generic Dictionary defined in System.Collections.Generic namespace
// It uses a hashtable data structure to store keys and values.
var colors = new Dictionary<string, string>
{
{"White","#FFFFFF" }
,{"Red","#FF0000" }
,{"Green","#0000FF" }
,{"Blue","#008000" }
};
Console.WriteLine(colors["Red"]); // #FF0000
// update value of existing key
colors["White"] = "#FFF";
// iterate over dictionary
foreach (var kv in colors)
{
Console.WriteLine($"Code of {kv.Key} is {kv.Value}");
}
// check if key is exist
if (!colors.ContainsKey("Yellow"))
{
// adds new key/value pair
colors.Add("Yellow", "#FFEF00"); // or colors["Yellow"] = "#FFEF00";
}
if (!colors.TryGetValue("Yellow", out var _))
{
colors.Add("Yellow", "#FFEF00");
}
// TryAdd does nothing if key already exist
if (!colors.TryAdd("Yellow", "#FFEF00"))
{
Console.WriteLine("key already exists");
}
}
}