如何修改KeyValuePair值?

时间:2012-11-19 13:23:54

标签: c# .net

当我尝试修改项目的值时,我遇到了一个问题,因为它只是一个只读字段。

KeyValuePair<Tkey, Tvalue>

我尝试了不同的替代方案,如:

Dictionary<Tkey, Tvalue>

但我有同样的问题。有没有办法将值字段设置为新值?

7 个答案:

答案 0 :(得分:98)

您无法修改它,您可以用新的替换它。

var newEntry = new KeyValuePair<Tkey, Tvalue>(oldEntry.Key, newValue);

或字典:

dictionary[oldEntry.Key] = newValue;

答案 1 :(得分:8)

KeyValuePair<TKey, TValue>是不可变的。您需要使用修改后的键或值创建一个新的。你下一步做什么取决于你的场景,你想要做什么......

答案 2 :(得分:8)

在这里,如果你想使KeyValuePair可变。

制作自定义课程。

public class KeyVal<Key, Val>
{
    public Key Id { get; set; }
    public Val Text { get; set; }

    public KeyVal() { }

    public KeyVal(Key key, Val val)
    {
        this.Id = key;
        this.Text = val;
    }
}

所以我们可以在KeyValuePair的任何地方使用它。

答案 3 :(得分:1)

KeyValuePair<TKey, TValue>是一个结构,而C#中的结构是值类型,并提到是不可变的。原因很明显,Dictionary<TKey,TValue>应该是高性能的数据结构。使用引用类型而不是值类型会占用过多的内存开销。与字典中直接存储的值类型不同,此外,还将为字典中的每个条目分配32位或64位引用。这些引用将指向条目实例的堆。总体性能会迅速下降。

Microsoft选择Dictionary<TKey,TValue>满足的结构而非类的规则:

✔️考虑到类型的实例较小且通常为短寿命或通常嵌入在其他对象中的情况,请定义结构而不是类。

❌除非结构具有以下所有特征,否则避免定义结构:

  • 它在逻辑上表示一个值,类似于基本类型(int,double等)。
  • 实例大小小于16个字节。
  • 这是一成不变的。
  • 不必经常装箱。

答案 4 :(得分:0)

您不能修改KeyValuePair,但是可以像这样修改字典值:

foreach (KeyValuePair<String, int> entry in dict.ToList())
{
    dict[entry.Key] = entry.Value + 1;
}

或类似这样:

foreach (String entry in dict.Keys.ToList())
{
    dict[entry] = dict[entry] + 1;
};

答案 5 :(得分:0)

KeyValuePair是不可变的

namespace System.Collections.Generic
{
  [Serializable]
  public struct KeyValuePair<TKey, TValue>
  {
    public KeyValuePair(TKey key, TValue value);
    public TKey Key { get; }
    public TValue Value { get; }
    public override string ToString();
  }
}

如果您要更新KeyValuePair中的任何现有值,则可以尝试删除现有值,然后添加修改后的值

例如:

var list = new List<KeyValuePair<string, int>>();
list.Add(new KeyValuePair<string, int>("Cat", 1));
list.Add(new KeyValuePair<string, int>("Dog", 2));
list.Add(new KeyValuePair<string, int>("Rabbit", 4));

int removalStatus = list.RemoveAll(x => x.Key == "Rabbit");

if (removalStatus == 1)
{
    list.Add(new KeyValuePair<string, int>("Rabbit", 5));
}

答案 6 :(得分:0)

Dictionary<long, int> _rowItems = new Dictionary<long, int>();
  _rowItems.Where(x => x.Value > 1).ToList().ForEach(x => { _rowItems[x.Key] = x.Value - 1; });

对于字典,我们可以根据某些条件以这种方式更新值。

相关问题