1. A dictionary is a collection of (key, value) pairs
2. Dictionary class is present in System.Collections.Generic namespace
3. When creating a dictionary, we need to specify the type for key and value
4. Dictionary provides fast lookups for values using keys.
5. keys in the dictionary must be unique
using System;
using System.Collections.Generic;
using System.Linq; //for count method
//dictionary is key of value pair
namespace Dictionary
{
class Program
{
static void Main(string[] args)
{
Customer C1 = new Customer()
{
ID = 101,
Name = "Mark",
Salary = 5000
};
Customer C2 = new Customer()
{
ID = 102,
Name = "Pam",
Salary = 6500
};
Customer C3 = new Customer()
{
ID = 119,
Name = "John",
Salary = 3500
};
Dictionary<int, Customer> dictionaryCustomers = new Dictionary<int, Customer>();
dictionaryCustomers.Add(C1.ID, C1);
dictionaryCustomers.Add(C2.ID, C2);
dictionaryCustomers.Add(C3.ID, C3);
Customer customer119 = dictionaryCustomers[119];
//Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", customer119.ID, customer119.Name, customer119.Salary);
foreach (KeyValuePair<int,Customer> customerKeyValuepair in dictionaryCustomers)
{
Console.WriteLine("ID = {0}", customerKeyValuepair.Key);
Customer cust = customerKeyValuepair.Value;
Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cust.ID, cust.Name, cust.Salary);
Console.WriteLine("----------------------------------------------");
}
foreach (int key in dictionaryCustomers.Keys)
{
Console.WriteLine("Key = {0}", key);
Console.WriteLine("----------------------------------------------");
}
foreach (Customer cust in dictionaryCustomers.Values)
{
Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cust.ID, cust.Name, cust.Salary);
}
//to check the key exists without getting any exception
Customer cust;
if (dictionaryCustomers.TryGetValue(101, out cust))
{
Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cust.ID, cust.Name, cust.Salary);
}
else
{
Console.WriteLine("The key is not found");
}
//total number of Items
Console.WriteLine("Total Items = {0}", dictionaryCustomers.Count);
//need to add "using System.Linq;" namespace
Console.WriteLine("Total Items = {0}", dictionaryCustomers.Count(kvp=>kvp.Value.Salary>4000));
//remove one key from dictionary
dictionaryCustomers.Remove(999);
//clear - remove all items from the dictionary
dictionaryCustomers.Clear();
//
//Customer[] customers = new Customer[3];
//customers[0] = C1;
//customers[1] = C2;
//customers[2] = C3;
List<Customer> customers = new List<Customer>();
customers.Add(C1);
customers.Add(C2);
customers.Add(C3);
Dictionary<int, Customer> dict = customers.ToDictionary(cust1 => cust1.ID, cust1 => cust1);
foreach (KeyValuePair<int, Customer> kvp in dict)
{
Console.WriteLine("Key ={0}", kvp.Key);
Customer cust1 = kvp.Value;
Console.WriteLine("ID = {0}, Name ={1}, Salary={2}", cust1.ID, cust1.Name, cust1.Salary);
}
}
}
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
}
}