Created
August 15, 2020 08:10
-
-
Save danielsimionescu/94ad9d490a97ff9dad22eb44d950172b to your computer and use it in GitHub Desktop.
C# Dictionary Methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace DictionaryMethods | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var store = new Dictionary<string, double> | |
{ | |
["peach"] = 15, | |
["grape"] = 23, | |
["lemon"] = 8, | |
["coconut"] = 10 | |
}; | |
var peachType = "peach"; | |
try | |
{ | |
store.Add(peachType, 21); | |
} | |
catch (ArgumentException ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
store.TryAdd(peachType, 21); | |
store.Remove("coconut"); | |
foreach (var item in store) | |
{ | |
Console.WriteLine(item.Key + " " + item.Value); | |
} | |
var key = "cherry"; | |
var foundValueByKey = store.ContainsKey(key) | |
? store[key].ToString() | |
: $@"Key ""{key}"" doesn't exist"; | |
Console.WriteLine(foundValueByKey); | |
var keyExists = store.ContainsKey(key); | |
if (keyExists) | |
{ | |
Console.WriteLine(store[key]); | |
} | |
else | |
{ | |
Console.WriteLine($"Key {key} doesn't exist"); | |
} | |
var totalFruitTypes = store.Count; | |
Console.WriteLine(totalFruitTypes); | |
store.TryGetValue("lemon", out double quantity); | |
Console.WriteLine(quantity); | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment