Remove from Dictionary by Key and Retrieve Value

后端 未结 6 494
广开言路
广开言路 2020-12-17 20:05

Is there a way to remove an entry from a Dictionary (by Key) AND retrieve it\'s Value in \"the same step?\"

For example, I\'m

6条回答
  •  -上瘾入骨i
    2020-12-17 20:48

    You can do it with an Extension method:

    public static string GetValueAndRemove(this Dictionary dict, int key)
    {
        string val = dict[key];
        dict.Remove(key);
        return val;    
    }
    
    static void Main(string[] args)
    {
        Dictionary a = new Dictionary();
        a.Add(1, "sdfg");
        a.Add(2, "sdsdfgadfhfg");
        string value = a.GetValueAndRemove(1);
    }
    

提交回复
热议问题