如何修改KeyValuePair值?


81

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

KeyValuePair<Tkey, Tvalue>

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

Dictionary<Tkey, Tvalue>

但是我有同样的问题。有没有一种方法可以将值字段设置为新值?


您是要更新特定值还是字典中的所有/大多数值?
J0HN 2012年

我尝试更新特定值。
Kimbo,2012年

Answers:


122

您无法修改它,可以将其替换为新的。

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

或字典:

dictionary[oldEntry.Key] = newValue;

谢谢你的帮助。词典中的部分正是我所需要的。
Kimbo,2012年

13

在这里,如果要使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中的任何地方使用它。


9

KeyValuePair<TKey, TValue>是一成不变的。您需要使用修改后的键或值创建一个新的。接下来的实际操作取决于您的方案,以及您实际要做什么...


我可以修改KeyValuePair <>。永远不要低估P / Invoke。
约书亚

1

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));
}

1

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

Microsoft选择Dictionary<TKey,TValue>符合结构的结构的规则如下:

如果类型的实例很小且通常是短寿命的或通常嵌入在其他对象中,则考虑定义结构而不是类。

VO避免定义结构,除非类型具有以下所有特征:

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

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;
};

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.