Can't add keyValuePair directly to Dictionary

后端 未结 8 1085
半阙折子戏
半阙折子戏 2020-12-18 18:45

I wanted to add a KeyValuePair to a Dictionary and I couldn\'t. I have to pass the key and the value separately, which must

相关标签:
8条回答
  • 2020-12-18 19:13

    What would be wrong with just adding it into your project as an extension?

    namespace System.Collection.Generic
    {
        public static class DictionaryExtensions
        {
            public static void AddKeyValuePair<K,V>(this IDictionary<K, V> me, KeyValuePair<K, V> other)
            {
                me.Add(other.Key, other.Value);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 19:15

    Backup a minute...before going down the road of the oversight, you should establish whether creating a new KeyValuePair is really so inefficient.

    First off, the Dictionary class is not internally implemented as a set of key/value pairs, but as a bunch of arrays. That aside, let's assume it was just a set of KeyValuePairs and look at efficiency.

    The first thing to notice is that KeyValuePair is a structure. The real implication of that is that it has to be copied from the stack to the heap in order to be passed as a method parameter. When the KeyValuePair is added to the dictionary, it would have to be copied a second time to ensure value type semantics.

    In order to pass the Key and Value as parameters, each parameter may be either a value type or a reference type. If they are value types, the performance will be very similar to the KeyValuePair route. If they are reference types, this can actually be a faster implementation since only the address needs to be passed around and very little copying has to be done. In both the best case and worst case, this option is marginally better than the KeyValuePair option due to the increased overhead of the KeyValuePair struct itself.

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