我试图将字典中键的值更改如下:
//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不能分配给。是只读的。我真正想要做的是在这里更改字典键的值,并给它分配另一个值。”
发布于 2019-01-18 20:30:56
这样做的唯一方法是删除并重新添加字典项。
为什么?这是因为字典工作在一个名为链接和桶的进程上(它类似于具有不同冲突解决策略的哈希表)。
当一个项被添加到一个字典中时,它会被添加到其键散列到的桶中,如果已经有一个实例,它就会被添加到一个链表中。如果您要更改密钥,则需要完成确定其所属位置的过程。因此,最简单、最理智的解决方案就是移除并重新添加项目。
溶液
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);
Side :从字典中添加和删除会带来一定的损失;如果您不需要快速查找,那么它可能更适合于根本不使用字典或使用其他策略。
https://stackoverflow.com/questions/54263933
复制