I am telling about creation of dictionary which can consist and store multiple information together. It does not involve any SQL table neither any SQL query nor any DB connectivity. It is much more useful for small applications and large applications having small information list.
Complete code showing the keywords and way to maintain a dictionary and perform various processing.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- // a dictionary to maintain the authors with their age
- Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
- AuthorList.Add("Manish", 35);
- AuthorList.Add("Mukesh", 25);
- AuthorList.Add("Praveen", 29);
- AuthorList.Add("Rajesh", 21);
- AuthorList.Add("Dinesh", 84);
- AuthorList.Add("Manisha Gupta", 22);
- // Remove item with key = 'Manisha Gupta'
- AuthorList.Remove("Manisha Gupta");
- //Find a key
- if (!AuthorList.ContainsKey("Manisha Gupta"))
- {
- AuthorList["Manisha Gupta"] = 22;
- Console.WriteLine("Key not found");
- Console.ReadLine();
- }
- else
- {
- Console.WriteLine("Key found");
- Console.ReadLine();
- }
- //Find a value
- if (!AuthorList.ContainsValue(9))
- {
- Console.WriteLine("Item not found");
- Console.ReadLine();
- }
- else
- Console.WriteLine("Item found");
- Console.ReadLine();
- //to read all the authors in the dictionary
- foreach (KeyValuePair<string, Int16> author in AuthorList)
- {
- Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
- Console.ReadLine();
- }
- // to count the number of authors in the authorlist
- Console.WriteLine("Count: {0}", AuthorList.Count);
- // Set Item value
- AuthorList["Mukesh"] = 20;
- // Get Item value
- Int16 age = Convert.ToInt16(AuthorList["Mukesh"]);
- // Get and display keys
- Dictionary<string, Int16>.KeyCollection keys = AuthorList.Keys;
- foreach (string key in keys)
- {
- Console.WriteLine("Key: {0}", key);
- Console.ReadLine();
- }
- // Get and display values
- Dictionary<string, Int16>.ValueCollection values = AuthorList.Values;
- foreach (Int16 val in values)
- {
- Console.WriteLine("Value: {0}", val);
- Console.ReadLine();
- }
- }
-
you can also change the type of dictionary being created as
Dictionary<string, string> AuthorList = new Dictionary<string, string>();
Dictionary<string,float> AuthorList = new Dictionary<string, float>();
Thus you can easily create the dictionary and use it in your applications.
If you have any query feel free to ask.
Join the conversation! Your thoughts help the community grow.