字典:无法将属性或索引器分配给:它是只读的

Muh*_*hid 4 c# setter dictionary key keyvaluepair

我正在尝试更改字典中 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];
            }

        }
Run Code Online (Sandbox Code Playgroud)

但它说“属性或索引器 KeyValuePair>.Key 不能分配给。是只读的。我真正想做的是在这里更改字典 Key 的值并为其分配另一个值。

AAA*_*ddd 8

这样做的唯一方法是删除并重新添加字典项

为什么?这是因为字典适用于称为链接和存储桶的过程(它类似于具有不同冲突解决策略的哈希表)

在此处输入图片说明

当一个项目被添加到字典中时,它被添加到它的键散列到的存储桶中,如果那里已经有一个实例,它会被添加到一个链表中。如果您要更改密钥,则需要经过确定其所属位置的过程。所以最简单和最明智的解决方案是删除并重新添加项目

解决方案

var data = SomeFunkyDictionary[key];
SomeFunkyDictionary.Remove(key);
SomeFunkyDictionary.Add(newKey,data);
Run Code Online (Sandbox Code Playgroud)

或者让你自己成为一个扩展方法

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

用法

SomeFunkyDictionary.ReplaceKey(oldKye,newKey);
Run Code Online (Sandbox Code Playgroud)

旁注:从字典中添加和删除会导致惩罚,如果您不需要快速查找,那么根本不使用字典或使用其他策略可能更合适。

  • 那是因为您修改了 foreach 循环内的字典。如果你想毫无例外地处理它,你可以尝试从中取出所有密钥并处理它们。“var 键 = SuggestedDictionary.Keys; foreach(键中的 var 键){ DoSomething(SuggestedDictionary[key]); }” (2认同)