我正在使用 C# 4.0。 我想使用 IDictionary 存储 (string,string) 对。 如下所示:
Dictionary<string, string> _tempDicData = new Dictionary<string, string>();
_tempDicData.Add("Hello", "xyz");
_tempDicData.Add("Hello", "aaa");
_tempDicData.Add("Hello", "qwert");
_tempDicData.Add("Hello", "foo");
_tempDicData.Add("Hello", "pqr");
_tempDicData.Add("Hello", "abc");
但出现错误:
An item with the same key has already been added.
那么如何在 IDictionary 中存储相同的 key ?
最佳答案
您不能将相同的项目添加到 IDictionary<K,T>
不止一次——这就是字典、关联容器的全部意义所在。但是您可以像这样替换现有的:
_tempDicData.Add("Hello", "xyz");
_tempDicData["Hello"] = "aaa";
如果每个键需要多个项目,您可以创建一个列表字典:
IDictionary<string,IList<string>> _tempDicData =
new Dictionary<string,IList<string>>();
IList<string> lst = new List<string>();
lst.Add("xyz");
lst.Add("aaa");
_tempDicData.Add("Hello", lst);
当您不确定某个键的列表是否存在时,您可以使用此模式添加新项:
IList<string> lst;
if (!_tempDicData.TryGetValue("Hello", out lst)) {
_tempDicData.Add("Hello", lst);
}
lst.Add("xyz");
lst.Add("aaa");
关于c# - 如何在字典中存储相同的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520667/