C#的字典表的键与值是对应的,键不能重复、也不能修改。
1、如果值是数组
代码可能这样写:
Dictionary<string, Array> Dict = new Dictionary<string, Array>();
string[] TableInfo = new string[2];
TableInfo[0] = "Computer";
TableInfo[1] = "16";
Dict.Add("计算机", TableInfo);
TableInfo[0] = "Printer";
TableInfo[1] = "8";
Dict.Add("打印机", TableInfo);
TableInfo[0] = "Scanner";
TableInfo[1] = "7";
Dict.Add("扫描仪", TableInfo);
这样的写法是不能得到正确结果的。
取值:
string[] AA1 = new string[2];
foreach (var item in Dict)
{
listBox1.Items.Add(item.Key);
AA1 = (string[])Dict[item.Key];
for (int i = 0; i < AA1.Length; i++)
{
listBox1.Items.Add(AA1[i]);
}
}
结果:
因为字典表中的值如果是数组,存储是数组的首项地址,存储的是一个引用地址。
正确的写法:
Dictionary<string, Array> Dict = new Dictionary<string, Array>();
string[] TableInfo1 = new string[2];
TableInfo1[0] = "Computer";
TableInfo1[1] = "16";
Dict.Add("计算机", TableInfo1);
string[] TableInfo2 = new string[2];
TableInfo2[0] = "Printer";
TableInfo2[1] = "8";
Dict.Add("打印机", TableInfo2);
string[] TableInfo3 = new string[2];
TableInfo3[0] = "Scanner";
TableInfo3[1] = "7";
Dict.Add("扫描仪", TableInfo3);
string[] AA1 = new string[2];
foreach (var item in Dict)
{
listBox1.Items.Add(item.Key);
AA1 = (string[])Dict[item.Key];
for (int i = 0; i < AA1.Length; i++)
{
listBox1.Items.Add(AA1[i]);
}
}
结果:
2、字典表的键更改
字典表中的键是不允许修改的,可以使用字典的todictionary方法来修改,就是使用一个临时字典表过度一下。
Dictionary<string, string> Dict = new Dictionary<string, string>();
Dict.Add("计算机", "Computer");
Dict.Add("打印机", "Printer");
Dict.Add("扫描仪", "Scanner");
listBox1.Items.Add("更改前");
foreach (var item in Dict)
{
listBox1.Items.Add(item.Key+"|"+item.Value);
}
Dict = Dict.ToDictionary(item => item.Key == "扫描仪" ? "扫描仪ABC" : item.Key, item => item.Value);
listBox1.Items.Add("更改后");
foreach (var item in Dict)
{
listBox1.Items.Add(item.Key + "|" + item.Value);
}
结果: