Dictionary in .NET C#: Syntax, Methods, and Example

Introduction

In C#, a dictionary is a generic collection that holds elements as pairs of keys and values. The Non-Generic Hashtable collection and the Generic Dictionary operate extremely similarly. The distinction is that we have to declare the type of both the keys and the values when we create the generic dictionary object. The namespace System.Collection.Generic. The dictionary's size automatically increases as new entries are added to the generic Dictionary<TKey, TValue> collection because it is dynamic in nature.

The following are some things to keep in mind when using C#'s Dictionary.

  • The value in the Generic Dictionary<TKey, TValue> Collection may be null if its type is a reference type, however, the key cannot be null in this collection.
  • In the Generic Dictionary<TKey, TValue> Collection, each key needs to be distinct. Replica keys are prohibited. An exception will be raised by the compiler if you attempt to add more than one key.
  • The elements in the Generic Dictionary<TKey, TValue> Collection are limited to storing only identical types.
  • The quantity of elements that a dictionary collection may include is known as its capacity.

Syntax

Dictionary<TKey, TValue> object_name = new Dictionary<TKey, TValue>();

Creating the Dictionary

Dictionary<string, object> employee = new Dictionary<string, object>();

Creating the elements in Dictionary

The dictionary provides the Add method, so we can use that method for adding the data to the dictionary.

Syntax

dictionary_object_name.Add(key_name, value);
Dictionary<string, object> employee = new Dictionary<string, object>();

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");

foreach (var item in employee)
{
    Console.WriteLine("{0} - {1}", item.Key, item.Value);
}

Dictionary

Modify elements in the Dictionary

The dictionary provides the modified element that has been inserted in the dictionary.

Syntax

dictionary_name[“keyname”] = value;
Dictionary<string, object> employee = new Dictionary<string, object>();

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");

foreach (var item in employee)
{
    Console.WriteLine("{0} - {1}", item.Key, item.Value);
}

employee["Location"] = "Surat";
employee["Rank"] = 134;

Console.WriteLine("\nModified data in dictionary.");
foreach (var item in employee)
{
    Console.WriteLine("{0} - {1}", item.Key, item.Value);
}

Employee

Check the key/value exists in the Dictionary

The dictionary provides a way to check if any key exists in the dictionary or not, or if you want to check the dictionary value, it also provides it to us.

Syntax

Dictionary_name.ContainsKey(“keyname”);

Dictionary_name.ContainsValue(“valuename”);
Dictionary<string, object> employee = new Dictionary<string, object>();

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");
employee["Rank"] = 134;

Console.WriteLine("Name Exists: {0}", employee.ContainsKey("Name"));

Console.WriteLine("Type Exists: {0}", employee.ContainsKey("Type"));

Console.WriteLine("Value Exists: {0}", employee.ContainsValue(1));

Console.WriteLine("Value Exists: {0}", employee.ContainsValue("Surat"));

Console

Remove element from the Dictionary

If you want to remove any elements from the dictionary, that is also possible; for that, we need to use the Remove() method.

Syntax

Dictionary_name.Remove(“keyname”);
Dictionary<string, object> employee = new Dictionary<string, object>();

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");
employee["Rank"] = 134;

Console.WriteLine("Total elements: {0}", employee.Count);

employee.Remove("Id");
Console.WriteLine("\nAfter removing Id, Total elements: {0}", employee.Count);

if (employee.ContainsKey("Salary"))
{
    employee.Remove("Salary");
}
else
{
    Console.WriteLine("\nThe proof key is not present in the dictionary.");
}

Remove method

Clear Elements from the Dictionary

If you want to remove all of the data from the dictionary, we need to use the Clear() method.

Syntax

Dictionary_name.Clear();
Dictionary<string, object> employee = new Dictionary<string, object>();

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");
employee["Rank"] = 134;

Console.WriteLine("Total elements: {0}", employee.Count);

employee.Clear();
Console.WriteLine("\nAfter clearing elements, Total elements: {0}", employee.Count);

Employee count

Get value from the Dictionary

For bringing the value from the dictionary, here are a couple of ways to bring the data.

  1. Key access
  2. TryGetValue

Syntax

Dictionary_name[“keyname”];

Dictionary_name.TryGetValue(“keyname”, out datatype object_name);
Dictionary<string, object> employee = new Dictionary<string, object>();

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");
employee["Rank"] = 134;

Console.WriteLine("Name: {0}", employee["Name"]);

_ = employee.TryGetValue("Rank", out var rank);
Console.WriteLine("\nRank: {0}", rank);

TryGetValue

If we want to bring data from the dictionary, then it will check the case-sensitive data.

If you want to case-insensitively check and bring the value from the dictionary, then we need to add that comparison type to the dictionary, and then it will check the case-insensitive data in the dictionary and bring the value.

Dictionary<string, object> employee = new Dictionary<string, object>();

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");
employee["Rank"] = 134;

_ = employee.TryGetValue("RAnk", out var rank);
Console.WriteLine("\nRank: {0}", rank);

Bring Data

Here is the code for the case-insensitively checking the dictionary and bringing the value from the dictionary.

Dictionary<string, object> employee = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

employee.Add("Id", 1);
employee.Add("Name", "Jaimin Shethiya");
employee.Add("Location", "Vadodara");
employee["Rank"] = 134;

_ = employee.TryGetValue("RAnk", out var rank);
Console.WriteLine("\nRank: {0}", rank);

Case-insensitively checking

Complex Type in Dictionary

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public int Rank { get; set; }

    public override string ToString()
    {
        var sb = new StringBuilder();
        sb.AppendLine($"{nameof(Id)} - {Id}, ");
        sb.AppendLine($"{nameof(Name)} - {Name}, ");
        sb.AppendLine($"{nameof(Location)} - {Location}, ");
        sb.AppendLine($"{nameof(Rank)} - {Rank}");

        return sb.ToString();
    }
}

Dictionary<int, Employee> employees = new Dictionary<int, Employee>();

employees.Add(1, new Employee { Id = 1, Name = "Jaimin Shethiya", Location = "Vadodara", Rank = 143 });
employees.Add(2, new Employee { Id = 2, Name = "Roshni Shethiya", Location = "Vadodara", Rank = 314 });
employees.Add(3, new Employee { Id = 3, Name = "Dwisha Shethiya", Location = "Vadodara", Rank = 615 });
employees.Add(4, new Employee { Id = 4, Name = "Dwiti Shethiya", Location = "Vadodara", Rank = 531 });

foreach (var employee in employees)
{
    Console.WriteLine("Key: {0} - Employee detail: {1}", employee.Key, employee.Value);
}

Complex Type

Another complex type is an illustration.

Dictionary<string, Action<int, int>> operations = new Dictionary<string, Action<int, int>>();
operations.Add("Addition", Addition);
operations.Add("Subtraction", Subtraction);
operations.Add("Multiplication", Multiplication);

_ = operations.TryGetValue("Addition", out Action<int, int> addition);
addition(10, 20);

_ = operations.TryGetValue("Subtraction", out Action<int, int> subtraction);
subtraction(50, 20);

_ = operations.TryGetValue("Multiplication", out Action<int, int> multiplication);
multiplication(10, 20);


static void Addition(int a, int b)
{
    Console.WriteLine("{0}, {1}, Addition is {2}", a, b, a + b);
}

static void Subtraction(int a, int b)
{
    Console.WriteLine("{0}, {1}, Subtraction is {2}", a, b, a - b);
}

static void Multiplication(int a, int b)
{
    Console.WriteLine("{0}, {1}, Multiplication is {2}", a, b, a * b);
}

Illustration

We learned the new technique and evolved together.

Happy coding!


Recommended Free Ebook
Similar Articles