C# 高效字典更改值或添加(键、值)(如果不在字典中)
假设我有一个字典C# 高效字典更改值或添加(键、值)(如果不在字典中),c#,performance,dictionary,C#,Performance,Dictionary,假设我有一个字典,其中TValue是一个引用类型 我想将TValue myNewValue分配给具有TKey myKey的元素。如果没有包含myKey的元素,我想添加它 我想用最少的GetHashCode()高效地完成这项工作: 代码应该类似于: private void AddOrReplace(TKey key, int value) { Dictionary<TKey, int> myDictionary = GetMyDictionary(...); if (
,其中TValue是一个引用类型
我想将TValue myNewValue分配给具有TKey myKey的元素。如果没有包含myKey的元素,我想添加它
我想用最少的GetHashCode()高效地完成这项工作:
代码应该类似于:
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);
}
}
private void addor replace(TKey key,int值)
{
Dictionary myDictionary=GetMyDictionary(…);
if(myDictionary.ContainsKey)(键)
{//字典中已存在密钥
myDictionary.key=值;
}
其他的
{//key尚未在字典中
添加(键、值);
}
}
这样TKey.GetHashCode()总是被调用两次
有没有一种更有效的方法,只调用一次TKey.GetHashCode?Dennis_E和Panagiotis Kanavos提供了答案。谢谢你们两位
我只是把它加在这里,以防有人认为他有同样的问题
描述如下:
属性值
类型:TValue
与指定键关联的值
- get如果找不到指定的键,get操作将抛出KeyNotFoundException
- setset操作使用指定的键创建新元素
顺便说一句,如果TValue是引用类型,这也不起作用。你想解决什么问题?GetHashCode应该是快速的,而不是返回唯一的哈希代码。它应该是一种比完整的Equals
比较更快的检查不平等性的方法。你为什么担心对GetHashCode
调用进行微优化?这真的是一个错误吗leneck在您的代码中?另外,为什么不直接调用myDict[key]=Value
?Panagiotis是正确的。为了澄清:myDictionary[key]=Value
将替换存在的值,并在不存在时添加它。
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);
}
}