What is dictionary in c#
What is dictionary in c#:-
Some methods of Dictionary class:-
When to use a dictionary over list in c#:-
Example of dictionary (1):-
Find():- This method of the List class loops thru each object in the list until a match is found. So, if you want to lookup a value using a key, dictionary is better for performance over list. So, use dictionary when you know the collection will be primarily used for lookups.
Example of Disctionay (2):- When use Disctionay
- A dictionary is a collection of (key, value) pairs.
- Dictionary class is present in System.Collections.Generic namespace.
- When creating a dictionary, we need to specify the type for key and value.
- Dictionary provides fast lookups for values using keys.
- Keys in the dictionary must be unique.
Some methods of Dictionary class:-
- TryGetValue()
- Count()
- Remove()
- Clear()
- Using LINQ extension methods with Dictionary
- Different ways to convert an array into a dictionary
When to use a dictionary over list in c#:-
Example of dictionary (1):-
Find():- This method of the List class loops thru each object in the list until a match is found. So, if you want to lookup a value using a key, dictionary is better for performance over list. So, use dictionary when you know the collection will be primarily used for lookups.
using System;em; using System.Collections.Generic; class DictionayDemo { public DictionayDemo() { Console.WriteLine("This is Dictionay Demo::\n"); } public void Show() { // Create a Dictionary, CustomerID is the key. Type is int // Customer object is the value. Type is Customer Dictionary dictionaryCustomers = new Dictionary (); // Create Customer Objects Customer customr1 = new Customer() { ID = 101, Name = "Santosh kumar singh", Salary = 5000 }; Customer customr2 = new Customer() { ID = 102, Name = "Reena kumari", Salary = 7000 }; Customer customr3 = new Customer() { ID = 104, Name = "Manorma arya", Salary = 5500 }; // Add customer objects to the dictionary dictionaryCustomers.Add(customr1.ID, customr1); dictionaryCustomers.Add(customr2.ID, customr2); dictionaryCustomers.Add(customr3.ID, customr3); // Retrieve the value (Customer object) from the dictionary, // using key (customer ID). The fastest way to get a value // from the dictionary is by using its key Console.WriteLine("Customer 101 in customer dictionary"); Customer customer101 = dictionaryCustomers[101]; Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", customer101.ID, customer101.Name, customer101.Salary); Console.WriteLine("--------------------------------------------------"); // It is also possible to loop thru each key/value pair in a dictionary Console.WriteLine("All customer keys and values in customer dictionary"); foreach (KeyValuePair customerKeyValuePair in dictionaryCustomers) { Console.WriteLine("Key = " + customerKeyValuePair.Key); Customer cust = customerKeyValuePair.Value; Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cust.ID, cust.Name, cust.Salary); } Console.WriteLine("--------------------------------------------------"); // You can also use implicitly typed variable VAR to // loop thru each key/value pair in a dictionary. But try // to avoid using var, as this makes your code less readable Console.WriteLine("All customer keys and values in customer dictionary"); foreach (var customerKeyValuePair in dictionaryCustomers) { Console.WriteLine("Key = " + customerKeyValuePair.Key); Customer cust = customerKeyValuePair.Value; Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cust.ID, cust.Name, cust.Salary); } Console.WriteLine("--------------------------------------------------"); // To get all the keys in the dictionary Console.WriteLine("All Keys in Customer Dictionary"); foreach (int key in dictionaryCustomers.Keys) { Console.WriteLine(key); } Console.WriteLine("--------------------------------------------------"); // To get all the values in the dictionary Console.WriteLine("All Customer objects in Customer Dictionary"); foreach (Customer customer in dictionaryCustomers.Values) { Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", customer.ID, customer.Name, customer.Salary); } // If you try to add a key that already exists in the dictionary you // will get an exception - An item with same key has already been // added. So, check if the key already exists if (!dictionaryCustomers.ContainsKey(101)) { dictionaryCustomers.Add(101, customr1); } // When accessing a dictionary value by key, make sure the dictionary // contains the key, otherwise you will get KeyNotFound exception. if (dictionaryCustomers.ContainsKey(110)) { Customer cus = dictionaryCustomers[110]; } else { Console.WriteLine("Key does not exist in the dictionary"); } } } class Customer { public int ID { get; set; } public string Name { get; set; } public int Salary { get; set; } } class TestDictionay { static void Main(string[] args) { DictionayDemo objDist = new DictionayDemo(); objDist.Show(); Console.ReadLine(); } }
Example of Disctionay (2):- When use Disctionay
using System; using System.Collections.Generic; using System.Collections; class DisctionayDemo2 { public DisctionayDemo2() { Console.WriteLine("When use dictionay demo::\n"); } public void Show() { Country country1 = new Country() { Code = "AUS", Name = "AUSTRALIA", Capital = "Canberra" }; Country country2 = new Country() { Code = "IND", Name = "INDIA ", Capital = "New Delhi" }; Country country3 = new Country() { Code = "USA", Name = "UNITED STATES", Capital = "Washington D.C." }; Country country4 = new Country() { Code = "GBR", Name = "UNITED KINGDOM", Capital = "London" }; Country country5 = new Country() { Code = "CAN", Name = "CANADA", Capital = "Ottawa" }; //List listCountries = new List (); //listCountries.Add(country1); //listCountries.Add(country2); //listCountries.Add(country3); //listCountries.Add(country4); //listCountries.Add(country5); Dictionary dictionaryCountries = new Dictionary (); dictionaryCountries.Add(country1.Code, country1); dictionaryCountries.Add(country2.Code, country2); dictionaryCountries.Add(country3.Code, country3); dictionaryCountries.Add(country4.Code, country4); dictionaryCountries.Add(country5.Code, country5); string strUserChoice = string.Empty; do { Console.WriteLine("Please enter country code"); string strCountryCode = Console.ReadLine().ToUpper(); // Find() method of the list class loops thru each object in the list until a match // is found. So, if you want to lookup a value using a key dictionary is better // for performance over list. // Country resultCountry = listCountries. // Find(country => country.Code == strCountryCode); Country resultCountry = dictionaryCountries.ContainsKey(strCountryCode) ? dictionaryCountries[strCountryCode] : null; if (resultCountry == null) { Console.WriteLine("The country code you enetered does not exist"); } else { Console.WriteLine("Name = " + resultCountry.Name + " Captial =" + resultCountry.Capital); } do { Console.WriteLine("Do you want to continue - YES or NO?"); strUserChoice = Console.ReadLine().ToUpper(); } while (strUserChoice != "NO" && strUserChoice != "YES"); } while (strUserChoice == "YES"); } } public class Country { public string Name { get; set; } public string Code { get; set; } public string Capital { get; set; } } class TestDictionay { static void Main(string[] args) { DisctionayDemo2 objDisct = new DisctionayDemo2(); objDisct.Show(); Console.ReadLine(); } }