How do I enumerate a dictionary?
Suppose I use foreach()
for dictionay enumeration. I can't update a key/value pair inside foreach()
. So I want some other method.
Dictionaries store unordered collections of values of the same type, which can be referenced and looked up through a unique identifier (also known as a key). An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.
In the C# language, enum (also called enumeration) is a user-defined value type used to represent a list of named integer constants. It is created using the enum keyword inside a class, structure, or namespace. It improves a program's readability, maintainability and reduces complexity.
C# Enumeration An enumeration is used in any programming language to define a constant set of values. For example, the days of the week can be defined as an enumeration and used anywhere in the program. In C#, the enumeration is defined with the help of the keyword 'enum'.
noun. the act of collecting. something that is collected; a group of objects or an amount of material accumulated in one location, especially for some purpose or as a result of some process: a stamp collection;a collection of unclaimed hats in the checkroom;a collection of books on Churchill.
To enumerate a dictionary you either enumerate the values within it:
Dictionary<int, string> dic; foreach(string s in dic.Values) { Console.WriteLine(s); }
or the KeyValuePairs
foreach(KeyValuePair<int, string> kvp in dic) { Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value); }
or the keys
foreach(int key in dic.Keys) { Console.WriteLine(key.ToString()); }
If you wish to update the items within the dictionary you need to do so slightly differently, because you can't update the instance while enumerating. What you'll need to do is enumerate a different collection that isn't being updated, like so:
Dictionary<int, string> newValues = new Dictionary<int, string>() { 1, "Test" }; foreach(KeyValuePair<int, string> kvp in newValues) { dic[kvp.Key] = kvp.Value; // will automatically add the item if it's not there }
To remove items, do so in a similar way, enumerating the collection of items we want to remove rather than the dictionary itself.
List<int> keys = new List<int>() { 1, 3 }; foreach(int key in keys) { dic.Remove(key); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With