在C#中嵌套嵌套字典中插入值

时间:2015-05-05 07:43:16

标签: c# dictionary

我通常在Java工作,而且我是C#的新手。我想存储一个<key , value>对来保存客户信息。在Java中,我使用Map,I C#Dictionary

在嵌套字典中插入时,C#会覆盖以前的innerDictionary记录。

这是我的代码

if (! outerDictionary.TryGetValue(senderID, out innerDictionary))
{
    innerDictionary = new Dictionary<int, string>();

    if (!innerDictionary.ContainsKey(numMessages))
    {
         outerDictionary.Add(senderID, innerDictionary);
         innerDictionary.Add(numMessages,txtSendMessage.Text);
    }
 }

这是输出

Sender ID = 1
Messages Count=2  Message Body:: Java Developer
....................................................
Sender ID = 1
Messages Count=3  Message Body:: Python Developer
Sender ID = 2
Messages Count=3  Message Body:: Python Developer
....................................................

欲望输出

Sender ID = 1
Messages Count=2  Message Body:: Java Developer
Sender ID = 2
Messages Count=3  Message Body:: Python Developer
....................................................

1 个答案:

答案 0 :(得分:1)

尝试这样做:

if (!outerDictionary.ContainsKey(senderID))
{
    outerDictionary[senderID] = new Dictionary<int, string>();
}
outerDictionary[senderID][numMessages] = txtSendMessage.Text;