how to create a dictionary in c# code example
Example 1: c sharp create dictionary
IDictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");
IDictionary<int, string> dict = new Dictionary<int, string>()
{
{1,"One"},
{2, "Two"},
{3,"Three"}
};
Example 2: 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 3: declare dictionary c#
var students2 = new Dictionary<int, StudentName>()
{
[111] = new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 },
[112] = new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } ,
[113] = new StudentName { FirstName="Andy", LastName="Ruth", ID=198 }
};
Example 4: c# dictionaries
IDictionary<int, string> dict = new Dictionary<int, string>();
Dictionary<int, string> dict = new Dictionary<int, string>();
Example 5: c sharp add item to dictionary
dict.Add(1,"One");