如果不在字典中,则高效字典更改值或添加(键,值)

时间:2015-10-26 10:33:24

标签: c# performance dictionary

假设我有一个词典<TKey, TValue&gt;,其中TValue是一个参考类型。

我想用TKey myKey将TValue myNewValue分配给元素。如果myKey没有元素,我想添加它。

我想用最小的GetHashCode()来有效地做到这一点:

private void AddOrReplace(TKey key, TValue value)
{
    Dictionary<TKey, TValue> myDictionary = GetMyDictionary(...);
    TValue existingValue;
    if (myDictionary.TryGetValue(key, out existingValue))
    {   // key already in dictionary
        existingValue = value;
    }
    else
    {   // key not in dictionary yet
        myDictionary.Add(key, value);
    }
}

这样,如果密钥已经存在,则调用TKey.GetHashCode()一次,但如果必须添加密钥,则调用两次。

但是,如果TValue是值类型

,这将不起作用
existingValue = value; // wrong! won't change the value in the dictionary

代码应该是这样的:

private void AddOrReplace(TKey key, int value)
{
    Dictionary<TKey, int> myDictionary = GetMyDictionary(...);
    if (myDictionary.ContainsKey(key)
    {   // key already in dictionary
        myDictionary.key = value;
    }
    else
    {   // key not in dictionary yet
        myDictionary.Add(key, value);
    }
}

这样TKey.GetHashCode()总是被调用两次。

是不是有更高效的方法,TKey.GetHashCode只被调用一次?

1 个答案:

答案 0 :(得分:0)

Dennis_E和Panagiotis Kanavos提供了答案。 非常感谢

我只是在这里添加它,以防有人认为他有同样的问题。

System.Collections.Generic.Dictionary.Item property (TKey)描述如下:

物业价值 类型:TValue 与指定键关联的值。

  • get 如果找不到指定的密钥,则get操作会抛出KeyNotFoundException,
  • 设置设置操作会创建具有指定键的新元素。