Dictionary enumeration in C#

前端 未结 4 1271
情歌与酒
情歌与酒 2020-12-29 04:16

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

4条回答
  •  盖世英雄少女心
    2020-12-29 04:22

    To enumerate a dictionary you either enumerate the values within it:

    Dictionary dic;
    
    foreach(string s in dic.Values)
    {
       Console.WriteLine(s);
    }
    

    or the KeyValuePairs

    foreach(KeyValuePair 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 newValues = new Dictionary() { 1, "Test" };
    foreach(KeyValuePair 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 keys = new List() { 1, 3 };
    foreach(int key in keys)
    {
       dic.Remove(key);
    }
    

提交回复
热议问题