The following program demonstrates How to Create a Generic Dictionary in C#.
In order to create a generic dictionary, we need to use the generic Dictionary class available in the System.Collections.Generic namespace. Since the Dictionary stores the collection of key-value pairs, we need to specify the data types for both keys and values. Here we take keys and values as integers. The Add() method inserts a key-value pair. Similarly, the Remove() method deletes a key-value pair.
using System;
using System.Collections.Generic;
namespace DictionaryClassDemo
{
// Demonstration of Generic Dictionary
class Program
{
static void Main(string[] args)
{
Dictionary<int, int> d1 = new Dictionary<int, int>();
d1.Add(1, 10);
d1.Add(2, 20);
d1.Add(3, 30);
d1.Add(4, 40);
d1.Add(5, 50);
d1.Add(6, 60);
d1.Add(7, 70);
d1.Add(8, 80);
d1.Add(9, 90);
// Item Property of the Dictionary
for (int i = 1; i <= 9; i++)
Console.WriteLine(d1[i].ToString());
// Count property
Console.WriteLine($"Total Key/Value pairs in the dictionary: {d1.Count}");
// Display the collection of keys in the dictionary
Console.WriteLine("Displying keys...");
foreach(int k in d1.Keys)
{
Console.Write(k+" ");
}
Console.WriteLine();
// Display the collection of values in the dictionary
Console.WriteLine("Displying values...");
foreach (int v in d1.Values)
{
Console.Write(v + " ");
}
Console.WriteLine();
//Removing Keys from the dictionary
d1.Remove(5);
d1.Remove(8);
//Display values after removing some keys
Console.WriteLine("Displaying values after removing some keys...");
foreach(KeyValuePair<int, int> k in d1)
{
Console.WriteLine($"Key: {k.Key}, Value: {k.Value}");
}
int a = 3;
Console.WriteLine($"Dictionary contains the Key {a}: {d1.ContainsKey(a)}");
a = 5;
Console.WriteLine($"Dictionary contains the Key {a}: {d1.ContainsKey(a)}");
a = 90;
Console.WriteLine($"Dictionary contains the value {a}: {d1.ContainsValue(a)}");
a = 80;
Console.WriteLine($"Dictionary contains the value {a}: {d1.ContainsValue(a)}");
//Using TryGetValues
Console.WriteLine("Displaying values in the Dictionary using TryGetValues()...");
int v1;
for (int i = 1; i <= 9; i++)
{
if(d1.TryGetValue(i, out v1))
Console.WriteLine(v1);
}
}
}
}
Output
Further Reading
How to Create Instance Variables and Class Variables in Python
Comparing Rows of Two Tables with ADO.NET
Example of Label and Textbox Control in ASP.NET
One Dimensional and Two Dimensuonal Indexers in C#