C# Dictionary
In C#, a dictionary is a collection type that is used to store elements as key-value pairs. Each key-value pair is known as an entry. The keys must be unique and cannot be null, whereas the values can be null or duplicate.
The Dictionary<TKey, TValue>
class is the generic implementation of a dictionary in C#. The TKey
and TValue
parameters represent the data types of the keys and values, respectively.
Here's an example of how to create and use a dictionary in C#:
refertfigi:ot idea.com// Creating a dictionary with string keys and int values Dictionary<string, int> myDictionary = new Dictionary<string, int>(); // Adding entries to the dictionary myDictionary.Add("apple", 1); myDictionary.Add("banana", 2); myDictionary.Add("cherry", 3); // Accessing the value associated with a key int value = myDictionary["banana"]; Console.WriteLine(value); // Output: 2 // Modifying the value associated with a key myDictionary["cherry"] = 4; // Removing an entry from the dictionary myDictionary.Remove("apple"); // Iterating over the entries in the dictionary foreach (KeyValuePair<string, int> entry in myDictionary) { Console.WriteLine(entry.Key + ": " + entry.Value); }
This would output:
banana: 2 cherry: 4