C# Dictionaries enable a variety of operations for manipulating data, such as adding, retrieving, and deleting key-value pairs, and more. Understanding these operations is crucial for efficient data handling in C#.
To add or update entries in a Dictionary, you use index notation or the Add method. If the key exists, the value is updated; if not, a new key-value pair is added. This flexibility allows for dynamic updates and additions to the Dictionary without needing a predefined structure.
The TryGetValue method retrieves the value associated with a specific key. It provides a safe way to access values, returning a boolean indicating success, and outputting the value if the key exists.
Checking if a key exists in the Dictionary can be done using the ContainsKey method. This method returns a boolean value — true if the key exists in the Dictionary, and otherwise false. This is particularly useful for conditionally handling data based on its existence in the Dictionary.
Deleting an entry is done using the Remove method followed by the key. This operation removes the specified key-value pair from the Dictionary, which is essential for actively managing the contents of the Dictionary.
The Count property provides the number of key-value pairs present in the Dictionary. This is especially useful when you need to know the total number of entries in the Dictionary.
Let’s see how these operations work in the context of a TaskManager class:
using System;
using System.Collections.Generic;
// Define TaskManager class
class TaskManager
{
private Dictionary<string, string> tasks;
public TaskManager()
{
// Initialize with an empty Dictionary
tasks = new Dictionary<string, string>();
}
public void AddUpdateTask(string taskName, string status)
{
// Add a new task or update an existing task
tasks[taskName] = status;
}
public string GetTaskStatus(string taskName)
{
// Use a nullable string type for status to address potential nullability
return tasks.TryGetValue(taskName, out string? status) ? status : "Not Found";
}
public void DeleteTask(string taskName)
{
// Removes a task using its name
if (tasks.ContainsKey(taskName))
{
tasks.Remove(taskName);
}
else
{
Console.WriteLine($"Task '{taskName}' not found.");
}
}
public int GetTaskCount()
{
// Returns the number of tasks in the TaskManager
return tasks.Count;
}
}
// Define Program class with Main method
class Program
{
static void Main(string[] args)
{
// Create a TaskManager instance
TaskManager myTasks = new TaskManager();
// Add tasks and update them
myTasks.AddUpdateTask("Buy Milk", "Pending");
Console.WriteLine(myTasks.GetTaskStatus("Buy Milk")); // Output: Pending
myTasks.AddUpdateTask("Buy Milk", "Completed");
Console.WriteLine(myTasks.GetTaskStatus("Buy Milk")); // Output: Completed
// Delete a task
myTasks.DeleteTask("Buy Milk");
Console.WriteLine(myTasks.GetTaskStatus("Buy Milk")); // Output: Not Found
// Add another task and get the count
myTasks.AddUpdateTask("Clean House", "In Progress");
Console.WriteLine(myTasks.GetTaskCount()); // Output: 1
}
}
This example showcases how to leverage Dictionary operations in C# to effectively manage data by adding, updating, retrieving, deleting entries, and checking the number of entries through a simulated Task Manager application.