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