In this article [Show more]
How to Read Dictionary in C#
In C#, the Dictionary<TKey, TValue> class provides a fast and efficient way to store key-value pairs. Reading data from a dictionary can be done in various ways depending on the structure of your program and the type of data you need. This article explains how to read a dictionary's keys and values in C# and provides practical examples.
Methods for Reading from a Dictionary
Accessing Values by Key
- Indexer (dictionary[key]): Retrieve the value directly using the key. An exception is thrown if the key does not exist.
- TryGetValue(key, out value): Retrieve the value safely without throwing exceptions.
Example: Using Indexer and TryGetValue
using System;
using System.Collections.Generic;
public class DictionaryReadExample
{
public static void Main()
{
// Create a dictionary with some key-value pairs
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 25 },
{ "Bob", 30 },
{ "Charlie", 35 }
};
// Using indexer to access values
Console.WriteLine($"Alice's age: {ages["Alice"]}");
Console.WriteLine($"Bob's age: {ages["Bob"]}");
// Using TryGetValue to access values safely
if (ages.TryGetValue("Charlie", out int charlieAge))
{
Console.WriteLine($"Charlie's age: {charlieAge}");
}
else
{
Console.WriteLine("Charlie not found.");
}
// Check for a non-existent key
if (!ages.TryGetValue("Dave", out int daveAge))
{
Console.WriteLine("Dave not found.");
}
}
}
Iterating Through the Dictionary
- foreach Loop: Use a foreach loop to iterate through all key-value pairs.
Example: Iterating with a Foreach Loop
using System;
using System.Collections.Generic;
public class DictionaryIterationExample
{
public static void Main()
{
// Create a dictionary with some key-value pairs
Dictionary<string, string> capitals = new Dictionary<string, string>
{
{ "USA", "Washington, D.C." },
{ "UK", "London" },
{ "France", "Paris" },
{ "Germany", "Berlin" }
};
// Iterate through the dictionary using a foreach loop
Console.WriteLine("List of capitals:");
foreach (KeyValuePair<string, string> kv in capitals)
{
Console.WriteLine($"{kv.Key}: {kv.Value}");
}
}
}
Using Keys and Values Collections
- Keys: Retrieve a collection of all the keys in the dictionary.
- Values: Retrieve a collection of all the values.
Example: Retrieving Keys and Values
using System;
using System.Collections.Generic;
public class DictionaryKeysValuesExample
{
public static void Main()
{
// Create a dictionary with some key-value pairs
Dictionary<string, int> products = new Dictionary<string, int>
{
{ "Laptop", 1200 },
{ "Smartphone", 800 },
{ "Tablet", 600 }
};
// Display all keys
Console.WriteLine("Product names:");
foreach (string key in products.Keys)
{
Console.WriteLine(key);
}
// Display all values
Console.WriteLine("\nProduct prices:");
foreach (int value in products.Values)
{
Console.WriteLine(value);
}
}
}
Conclusion
In C#, reading data from a Dictionary<TKey, TValue> can be achieved using indexers, TryGetValue, and by iterating through the collection. Understanding these approaches helps ensure efficient and error-free data access in your applications.