🕵️ SicherheitslückenHak5: Hackers Just Poisoned the Rust Supply Chain | Threat Wire(01.09.2026 um 14:00 Uhr)
🕵️ SicherheitslückenHak5: Hackers Found a Way Into Humanoid Robots | Threat Wire(04.09.2026 um 15:04 Uhr)
🔧 AI Nachrichten Bits und so #1021 (Passwort für Laufwerk)(31.08.2026 um 22:15 Uhr)
🔧 AI Nachrichten Bits und so #1022 (Wie Weißbier)(06.09.2026 um 20:39 Uhr)
🍏 iOS / Mac OSHue-App 6.0 ist da: das sind die Neuerungen(07.09.2026 um 17:21 Uhr)
🕵️ SicherheitslückenHak5: Hackers Just Poisoned the Rust Supply Chain | Threat Wire(01.09.2026 um 14:00 Uhr)
🕵️ SicherheitslückenHak5: Hackers Found a Way Into Humanoid Robots | Threat Wire(04.09.2026 um 15:04 Uhr)
🔧 AI Nachrichten Bits und so #1021 (Passwort für Laufwerk)(31.08.2026 um 22:15 Uhr)
🔧 AI Nachrichten Bits und so #1022 (Wie Weißbier)(06.09.2026 um 20:39 Uhr)
🍏 iOS / Mac OSHue-App 6.0 ist da: das sind die Neuerungen(07.09.2026 um 17:21 Uhr)

🔧 Programmierung 🕛 kürzlich 4 Min Lesezeit
0

C# Dictionary p2

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

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






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

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






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






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

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






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






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






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






CODE
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;
}
}












Step 2: The Country Class



The Country class models each country’s data.




CODE
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;
}
}












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






CODE
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.");
}
}
}
}












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




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

Country Details:
Name: Norway
Region: Europe
Population: 5,379,475






Invalid Key Lookup




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

Country not found.












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!

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
1 Quelle
Hackers Just Poisoned the Rust Supply Chain | Threat Wire
1 Quelle
Hackers Found a Way Into Humanoid Robots | Threat Wire
1 Quelle
Bits und so #1021 (Passwort für Laufwerk)
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten C# Dictionary p2

Thematisch verwandte Begriffe: Dictionary · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...