我正在尝试更改字典中 Keys 的值,如下所示:
//This part loads the data in the iterator
List<Recommendations> iterator = LoadBooks().ToList();
//This part adds the data to a list
List<Recommendations> list = new List<Recommendations>();
foreach (var item in iterator.Take(100))
{
list.Add(item);
}
//This part adds Key and List as key pair value to the Dictionary
if (!SuggestedDictionary.ContainsKey(bkName))
{
SuggestedDictionary.Add(bkName, list);
}
//This part loops over the dictionary contents
for (int i = 0; i < 10; i++)
{
foreach (var entry in SuggestedDictionary)
{
rec.Add(new Recommendations() { bookName = entry.Key, Rate = CalculateScore(bkName, entry.Key) });
entry.Key = entry.Value[i];
}
}
但它说“属性或索引器 KeyValuePair>.Key 不能分配给。是只读的。我真正想做的是在这里更改字典 Key 的值并为其分配另一个值。
最佳答案
这样做的唯一方法是删除并重新添加字典项
为什么?这是因为字典适用于称为链接和存储桶的过程(它类似于具有不同冲突解决策略的哈希表)
当一个项目被添加到字典中时,它会被添加到它的键散列到的存储桶中,如果那里已经有一个实例,它会被添加到一个链表中。如果您要更改 key ,则需要经过确定其所属位置的过程。所以最简单和最明智的解决方案是删除并重新添加项目
解决方案
var data = SomeFunkyDictionary[key];
SomeFunkyDictionary.Remove(key);
SomeFunkyDictionary.Add(newKey,data);
或者让你自己成为一个扩展方法
public static class Extensions
{
public static void ReplaceKey<T, U>(this Dictionary<T, U> source, T key, T newKey)
{
if(!source.TryGetValue(key, out var value))
throw new ArgumentException("Key does not exist", nameof(key));
source.Remove(key);
source.Add(newKey, value);
}
}
用法
SomeFunkyDictionary.ReplaceKey(oldKye,newKey);
旁注 :从字典中添加和删除会导致惩罚,如果您不需要快速查找,那么根本不使用字典或使用其他策略可能更合适。
关于c# - 字典:无法将属性或索引器分配给:它是只读的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54263933/