Skip to content

Instantly share code, notes, and snippets.

@danielsimionescu
Created August 15, 2020 08:10
Show Gist options
  • Save danielsimionescu/94ad9d490a97ff9dad22eb44d950172b to your computer and use it in GitHub Desktop.
Save danielsimionescu/94ad9d490a97ff9dad22eb44d950172b to your computer and use it in GitHub Desktop.
C# Dictionary Methods
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