Dictionaries help you store and find data quickly using keys. You use methods to add, check, or get values easily.
0
0
Dictionary methods and access patterns in C Sharp (C#)
Introduction
You want to store phone numbers with names as keys.
You need to check if a word exists in a list quickly.
You want to update a value for a specific key.
You want to loop through all keys and values to display them.
Syntax
C Sharp (C#)
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(); dict.Add(key, value); var value = dict[key]; bool hasKey = dict.ContainsKey(key); dict.TryGetValue(key, out value);
Use Add to insert new key-value pairs.
Use ContainsKey to check if a key exists before accessing it.
Examples
Adds "apple" with value 3, then gets the value using the key.
C Sharp (C#)
var dict = new Dictionary<string, int>(); dict.Add("apple", 3); int count = dict["apple"];
Checks if "banana" exists before trying to get its value to avoid errors.
C Sharp (C#)
if (dict.ContainsKey("banana")) { Console.WriteLine(dict["banana"]); } else { Console.WriteLine("No banana found"); }
Safely tries to get the value for "orange" without throwing an error if the key is missing.
C Sharp (C#)
if (dict.TryGetValue("orange", out int orangeCount)) { Console.WriteLine(orangeCount); } else { Console.WriteLine("No orange found"); }
Loops through all key-value pairs and prints them.
C Sharp (C#)
foreach (var pair in dict) {
Console.WriteLine($"{pair.Key}: {pair.Value}");
}Sample Program
This program creates a dictionary of fruits and their counts. It shows how to add items, check for keys, safely get values, and loop through all items.
C Sharp (C#)
using System; using System.Collections.Generic; class Program { static void Main() { var fruits = new Dictionary<string, int>(); fruits.Add("apple", 5); fruits.Add("banana", 2); if (fruits.ContainsKey("apple")) { Console.WriteLine($"Apple count: {fruits["apple"]}"); } if (fruits.TryGetValue("orange", out int orangeCount)) { Console.WriteLine($"Orange count: {orangeCount}"); } else { Console.WriteLine("No orange found"); } Console.WriteLine("All fruits:"); foreach (var fruit in fruits) { Console.WriteLine($"{fruit.Key}: {fruit.Value}"); } } }
OutputSuccess
Important Notes
Accessing a key that does not exist without checking causes an error.
Use TryGetValue to avoid exceptions when unsure if a key exists.
Dictionary keys must be unique; adding a duplicate key causes an error.
Summary
Dictionaries store data with unique keys for fast access.
Use Add, ContainsKey, and TryGetValue to manage dictionary data safely.
Loop through dictionaries with foreach to see all keys and values.