DEV Community

mohamed Tayel
mohamed Tayel

Posted on

C# Dictionary p2

Dictionaries are an integral part of efficient data management in C#. In this article, we’ll dive deeper into how to work with dictionaries, focusing on their unique behavior, common pitfalls, and advanced techniques. Building upon our previous work with Excel integration, we’ll also enhance our application to dynamically populate a dictionary and perform safe, user-friendly lookups of country details using three-letter codes.


Keys Are Unique

One of the fundamental differences between dictionaries and lists is that dictionary keys must be unique. This ensures data consistency but also introduces potential exceptions when trying to add duplicate keys.

Key Uniqueness Example

var countryDictionary = new Dictionary<string, string>
{
    { "NOR", "Norway" }
};

// Adding a duplicate key throws an exception
// countryDictionary.Add("NOR", "New Norway"); // InvalidOperationException
Enter fullscreen mode Exit fullscreen mode

In contrast, lists allow duplicate entries without issue, as they rely on positional indices.


The Uncertainty of Dictionary Lookups

While lists and arrays offer predictable indices for data access, dictionaries rely on the presence of keys, which might not always exist. Attempting to look up a key that doesn’t exist in the dictionary throws an exception.

Invalid Lookup Example

var countryDictionary = new Dictionary<string, string>
{
    { "NOR", "Norway" }
};

// Attempting to access a non-existent key
// string country = countryDictionary["MUS"]; // KeyNotFoundException
Enter fullscreen mode Exit fullscreen mode

This is where the TryGetValue method becomes invaluable.


Looking Up Items Safely with TryGetValue

The TryGetValue method allows for safe lookups, ensuring no exceptions are thrown if the key isn’t found. It returns a boolean indicating whether the key exists and outputs the value if present.

TryGetValue Example

if (countryDictionary.TryGetValue("MUS", out var country))
{
    Console.WriteLine($"Country: {country}");
}
else
{
    Console.WriteLine("Country not found.");
}
Enter fullscreen mode Exit fullscreen mode

This pattern is especially useful in dynamic applications where the presence of keys can’t be guaranteed.


Integrating Dictionaries with Excel Data

We’ll now enhance our country lookup application to leverage dictionaries for efficient key-based retrieval. This builds on the ExcelReaderWriter class and Excel setup we’ve used previously.


Step 1: Updating the ExcelReaderWriter Class

The ExcelReaderWriter class will include a method for populating a dictionary with data from the Excel file.

Method to Populate a Dictionary

using OfficeOpenXml;
using System.Collections.Generic;
using System.IO;

public class ExcelReaderWriter
{
    private readonly string _filePath;

    public ExcelReaderWriter(string filePath)
    {
        _filePath = filePath;
    }

    public Dictionary<string, Country> ReadAllCountriesIntoDictionary()
    {
        var countries = new Dictionary<string, Country>();

        using (var package = new ExcelPackage(new FileInfo(_filePath)))
        {
            var worksheet = package.Workbook.Worksheets["Countries"];
            int row = 2;

            while (worksheet.Cells[row, 1].Value != null)
            {
                var name = worksheet.Cells[row, 1].Value?.ToString();
                var code = worksheet.Cells[row, 2].Value?.ToString();
                var region = worksheet.Cells[row, 3].Value?.ToString();
                var population = int.Parse(worksheet.Cells[row, 4].Value?.ToString() ?? "0");

                var country = new Country(name, code, region, population);
                countries.Add(code, country); // Add key-value pairs
                row++;
            }
        }

        return countries;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: The Country Class

The Country class models each country’s data.

public class Country
{
    public string Name { get; }
    public string Code { get; }
    public string Region { get; }
    public int Population { get; }

    public Country(string name, string code, string region, int population)
    {
        Name = name;
        Code = code;
        Region = region;
        Population = population;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Building the Interactive Program

We’ll implement a program that:

  1. Populates a dictionary from the Excel file.
  2. Allows users to search for countries by their three-letter codes.
  3. Uses TryGetValue for safe lookups.

Interactive Program

using System;

class Program
{
    static void Main(string[] args)
    {
        string filePath = "Countries.xlsx";
        var excelHandler = new ExcelReaderWriter(filePath);

        Console.WriteLine("Reading all countries into a dictionary...");
        var countryDictionary = excelHandler.ReadAllCountriesIntoDictionary();

        while (true)
        {
            Console.WriteLine("\nEnter a three-letter country code (or type 'exit' to quit):");
            string inputCode = Console.ReadLine()?.ToUpper();

            if (inputCode == "EXIT")
                break;

            if (countryDictionary.TryGetValue(inputCode, out var country))
            {
                Console.WriteLine($"\nCountry Details:");
                Console.WriteLine($"Name: {country.Name}");
                Console.WriteLine($"Region: {country.Region}");
                Console.WriteLine($"Population: {PopulationFormatter.FormatPopulation(country.Population)}");
            }
            else
            {
                Console.WriteLine("\nCountry not found.");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Features Demonstrated

  1. Safe Lookups: Avoid exceptions using TryGetValue.
  2. Dynamic Data Handling: Populate dictionaries from Excel dynamically.
  3. User Interaction: Interactive console application for searching countries.
  4. Efficient Retrieval: Fast lookups using dictionary keys.

Expected Output

Valid Key Lookup

Enter a three-letter country code (or type 'exit' to quit):
NOR

Country Details:
Name: Norway
Region: Europe
Population: 5,379,475
Enter fullscreen mode Exit fullscreen mode

Invalid Key Lookup

Enter a three-letter country code (or type 'exit' to quit):
XYZ

Country not found.
Enter fullscreen mode Exit fullscreen mode

Conclusion

This article showcased the power of dictionaries for efficient data management, emphasizing unique keys and safe lookup techniques. By combining dictionaries with dynamic Excel integration, we created a scalable, user-friendly country lookup application.

This approach is perfect for applications that require fast lookups, meaningful keys, and robust error handling. Expand further by adding features like exporting results to Excel, filtering by region, or validating user input. Happy coding!

Top comments (0)