using Dictionary c# code example
Example 1: access dic by key c#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("windows", 5);
if (dictionary.ContainsKey("apple"))
{
int value = dictionary["apple"];
Console.WriteLine(value);
}
if (!dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false);
}
}
}
Example 2: c# dictionaries
IDictionary<int, string> dict = new Dictionary<int, string>();
Dictionary<int, string> dict = new Dictionary<int, string>();
Example 3: dictionary c#
IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1,"One");
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
foreach(KeyValuePair<int, string> kvp in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach(var kvp in cities)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
Example 4: c sharp add item to dictionary
dict.Add(1,"One");