A dictionary in C#, is a generic data type that stores a set of values with their corresponding keys internally for faster data retrieval.
The operation of finding the value associated with a key is called lookup or indexing.
Dictionay provide type safety and type casting(Generic concept)
Dictionary( Dictionary<TKey, TValue>) is a generic type, Hashtable is not
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dictionary
{
class Program
{
static void Main(string[] args)
{
try
{
Dictionary<string, Int16> list = new Dictionary<string, Int16>();
list.Add("Manu", 1);
list.Add("Akhtar", 2);
list.Add("Pitambar", 3);
list.Add("Ratan", 4);
// list.Add("Manu", 1);// An item with the same key has already been added. argument exception was unhandeld
//"is check the pair of values and keys"
list["Manu"] = 11; // insert new value and keys into dictionary.
//If keys our values exists it will update this, Its called Item property
Console.WriteLine("Data are given below:================");
foreach (KeyValuePair<string, Int16> member in list)
{
Console.WriteLine("key = {0}, value = {1}", member.Key, member.Value);
}
Console.WriteLine("Count ={0}", list.Count());
Dictionary<string, Int16>.KeyCollection keys = list.Keys;
Console.WriteLine("keys are given below:================");
foreach (string key in keys)
{
Console.WriteLine("Key: {0}", key);
}
Dictionary<string, Int16>.ValueCollection values = list.Values; // return object of value collection type
Console.WriteLine("Value are given below:================");
foreach (Int16 value in values)
{
Console.WriteLine("Values: {0}", value);
}
Console.WriteLine("Remove method :");
// list.Remove("Manu");
foreach (string key in keys)
{
Console.WriteLine("Key: {0}", key);
}
Console.WriteLine("Clear method :");
//list.Clear();
foreach (string key in keys)
{
Console.WriteLine("Key :{0}", key);
}
if (list.ContainsKey("Manu"))
{
Console.WriteLine("yes key exist in dictionary");
}
if (list.ContainsValue(3))
{
Console.WriteLine("yes value exist in dictionary");
}
// list.Add("Charpcorner", 7);
// Copy Dictionary Data into new Dictionary
Dictionary<string, Int16> copydict = new Dictionary<string, Int16>(list);
list.Add("Charpcorner", 6);
Console.WriteLine("New Dictionary coydict Data is::::");
foreach (var v in copydict)
{
Console.WriteLine(v);
}
Console.WriteLine("Add new item will not affect to copy dictionary item");
foreach (string key in keys)
{
Console.WriteLine("Key: {0}", key);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}