Is there a more elegant way of adding an item to a Dictionary<> safely?

后端 未结 5 752
梦如初夏
梦如初夏 2020-12-13 16:37

I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a \"key already exists in dictionary

相关标签:
5条回答
  • 2020-12-13 17:12

    simply

    dict[key] = view;
    

    From the MSDN documentation of Dictionary.Item

    The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

    My emphasis

    0 讨论(0)
  • 2020-12-13 17:18

    Although using the indexer is clearly the right answer for your specific problem, another more general answer to the problem of adding additional functionality to an existing type would be to define an extension method.

    Obviously this isn't a particularly useful example, but something to bear in mind for the next time you find a real need:

    public static class DictionaryExtensions
    {
        public static void SafeAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, 
                                                 TKey key, TValue value)
        {
            dict[key] = value;
        }
    }
    
    0 讨论(0)
  • 2020-12-13 17:19

    Just use the indexer - it will overwrite if it's already there, but it doesn't have to be there first:

    Dictionary<string, object> currentViews = new Dictionary<string, object>();
    currentViews["Customers"] = "view1";
    currentViews["Customers"] = "view2";
    currentViews["Employees"] = "view1";
    currentViews["Reports"] = "view1";
    

    Basically use Add if the existence of the key indicates a bug (so you want it to throw) and the indexer otherwise. (It's a bit like the difference between casting and using as for reference conversions.)

    If you're using C# 3 and you have a distinct set of keys, you can make this even neater:

    var currentViews = new Dictionary<string, object>()
    {
        { "Customers", "view2" },
        { "Employees", "view1" },
        { "Reports", "view1" },
    };
    

    That won't work in your case though, as collection initializers always use Add which will throw on the second Customers entry.

    0 讨论(0)
  • 2020-12-13 17:30

    As usual John Skeet gets in there with lighting speed with the right answer, but interestingly you could also have written your SafeAdd as an Extension Method on IDictionary.

    public static void SafeAdd(this IDictionary<K, T>. dict, K key, T value)...
    
    0 讨论(0)
  • 2020-12-13 17:32

    What's wrong with...

    dict[key] = view;
    

    It'll automatically add the key if it's non-existent.

    0 讨论(0)
提交回复
热议问题