c# - 如何在字典中存储相同的键?

标签 c# c#-4.0 idictionary

我正在使用 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/

相关文章:

c# - 运行托管代码的非托管线程

sql - 如何在sql查询中传递整型变量

c# - IEnumerable<KeyValuePair<string, UserInformation>> vs IDictionary<string,UserInformation>

c# - 如何将字典列表转换为 IDictionary “C#”

c# - 无法在 Visual Studio 调试器中查看字典内容

c# - GC.GetTotalMemory的使用及其返回值

C# - Windows Server 2008 和 IIS7 上来自 NetApi32.dll 的 NetUseAdd

c# - 此 SqlTransaction 已完成;它不再可用,为什么?

asp.net-mvc - 在 ASP.NET MVC 3 Action 方法中并行运行任务

c# - c#中的if返回语句