简体   繁体   English

如何在字典C#中替换int值

[英]How can I replace int values in a dictionary C#

I am wondering how I could replace int values in a dictionary in C#. 我想知道如何在C#中替换字典中的int值。 The values would look something like this. 这些值看起来像这样。

  • 25,12 25,12
  • 24,35 24,35
  • 12,34 12,34
  • 34,12 34,12

I was wondering how I could only replace one line. 我想知道如何只能替换一条线。 For example if I wanted to replace the first line with a new value of 12,12. 例如,如果我想用新的值12,12替换第一行。 And it wouldn't replace any of the other '12' values in the dictionary. 并且它不会替换字典中的任何其他“ 12”值。

A Dictionary<TInt, TValue> makes use of what are known as indexers. Dictionary<TInt, TValue>利用了所谓的索引器。 In this case, these are used to access elements in the dictionary by key, hence: 在这种情况下,这些键用于通过键访问字典中的元素,因此:

dict[25] would return 12 . dict[25]将返回12

Now, according to what you want to do is to have a key of 12 and a value of 12 . 现在,根据您要执行的操作,将键的值设置为12并将值的值设置为12 Unfortunately, you cannot replace entries in a dictionary by key, so what you must do is: 不幸的是,您不能用键替换字典中的条目,因此您必须做的是:

if(dict.ContainsKey(25))
{
    dict.Remove(25);
}
if(!dict.ContainsKey(12))
{
    dict.Add(12, 12);
}

Note: In the values you supplied, there is already a key-value pair with 12 as its key, so you would not be allowed to add 12,12 to the dictionary as if(!dict.ContainsKey(12)) would return false. 注意:在您提供的值中,已经有一个键值对,其键为12 ,因此您将不允许在字典中添加12,12 ,就像if(!dict.ContainsKey(12))会返回false一样。 。

You cannot replace the first line with 12, 12 because there is another key value pair with 12 as it's key. 您不能用12, 12替换第一行12, 12因为还有另一个键值为12的键值对。 And you cannot have duplicate keys in a dictionary. 而且字典中不能有重复的键。

Anyway you may do such things like this: 无论如何,您可能会执行以下操作:

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(25, 12);
myDictionary.Add(24, 35);

//remove the old item
myDictionary.Remove(25);

//add the new item
myDictionary.Add(12, 12);

EDIT: if you are going to save some x,y positions I would suggest you creating a class named Point and use a List<Point> . 编辑:如果您要保存一些x,y位置,我建议您创建一个名为Point的类并使用List<Point> Here is the code: 这是代码:

class Point
{
    public double X {get; set;}
    public double Y {get; set;}

    public Point(double x, double y)
    {
        this.X = x;
        this.Y = y;
    }
}

Then: 然后:

List<Point> myList =new List<Point>();
myList.Add(new Point(25, 13));

In Dictionaries, the keys must be unique. 在字典中,键必须是唯一的。

In case the key need not be unique, you could use a List<Tuple<int, int>> or List<CustomClass> with CustomClass containing two integer fields. 如果键不必唯一,则可以使用List<Tuple<int, int>>List<CustomClass>其中CustomClass包含两个整数字段。 Then you may add or replace the way you want. 然后,您可以添加或替换所需的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM