更改字典的键

JLo*_*ott 6 c# dictionary

我对词典很新.我大约6小时前开始使用它们的新意义:p.无论如何,我想知道是否有办法改变字典的键.

这是我的字典:

Dictionary<string, string> Information = new Dictionary<string, string>();
Run Code Online (Sandbox Code Playgroud)

这是我添加到字典的方式(每次用户输入信息并点击按钮时都会触发:

Information.Add(txtObjectNumber.Text, addressCombined);
Run Code Online (Sandbox Code Playgroud)

用户需要能够编辑这两个字段以及删除整个记录.

所以应用程序需要添加txtNumbertxtComments在哪里txtNumber = txtObjectNumber

谢谢您的帮助.

Arr*_*ran 11

无法直接修改密钥.您必须将其删除并重新添加.


Kri*_*ten 3

关键是允许您稍后找到数据(“值”)的机制。

例如,如果你这样做了

information.Add("Kris", "Vandermotten");
Run Code Online (Sandbox Code Playgroud)

如果您认识“Kris”,您稍后就能找到“Vandermotten”。

现在在这种情况下,改变意味着什么“Kris”您将数据放入“Kris”名下,并希望通过搜索“Bob”将其取回?你不会找到它。

在某种程度上,字典键非常类似于关系数据库中的主键。指的是值的逻辑同一性。因此,一方面,他们应该唯一地标识它。

所以也许这个例子没有意义。也许像

information.Add(42, new Person("Kris", "Vandermotten")
Run Code Online (Sandbox Code Playgroud)

更有意义。那么问题当然是:42 是什么?有时这样的密钥有一个自然的候选者,例如员工号码或其他东西,有时则没有。

当没有时,也许你需要做

List<Person> information = new List<Person>();

information.Add(new Person("Kris", "Vandermotten"));
Run Code Online (Sandbox Code Playgroud)

当然,如果 Person 对象允许更改名字属性,并且这就是您想要做的,那么就这样做。但“更改字典键”对我来说没有多大意义。