Dha*_*ari 1 c# idictionary c#-4.0
我正在使用C#4.0.我想使用IDictionary存储(字符串,字符串)对.如下:
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");
Run Code Online (Sandbox Code Playgroud)
但得到一个错误:
An item with the same key has already been added.
Run Code Online (Sandbox Code Playgroud)
那么如何在IDictionary中存储相同的密钥?
您不能IDictionary<K,T>多次添加相同的项目- 这是字典的整个点,一个关联容器.但是你可以像这样替换现有的:
_tempDicData.Add("Hello", "xyz");
_tempDicData["Hello"] = "aaa";
Run Code Online (Sandbox Code Playgroud)
如果每个键需要多个项目,您可以创建列表字典:
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);
Run Code Online (Sandbox Code Playgroud)
如果您不确定密钥列表是否存在,则可以使用此模式添加新项:
IList<string> lst;
if (!_tempDicData.TryGetValue("Hello", out lst)) {
_tempDicData.Add("Hello", lst);
}
lst.Add("xyz");
lst.Add("aaa");
Run Code Online (Sandbox Code Playgroud)