I usually work in Java and I am new to C#. I would like to store a <key , value>
pair to save client information. In Java, I use Map
, I C# Dictionary
.
我通常在Java工作,而且我是C#的新手。我想存储一个
During insertion in a nested dictionary, C# overrides the previous innerDictionary record.
在嵌套字典中插入期间,C#会覆盖以前的innerDictionary记录。
Here is my code
这是我的代码
if (! outerDictionary.TryGetValue(senderID, out innerDictionary))
{
innerDictionary = new Dictionary<int, string>();
if (!innerDictionary.ContainsKey(numMessages))
{
outerDictionary.Add(senderID, innerDictionary);
innerDictionary.Add(numMessages,txtSendMessage.Text);
}
}
Here Is Output
这是输出
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
....................................................
Desire Output
Sender ID = 1
Messages Count=2 Message Body:: Java Developer
Sender ID = 2
Messages Count=3 Message Body:: Python Developer
....................................................
1 个解决方案
#1
Try doing it this way:
尝试这样做:
if (!outerDictionary.ContainsKey(senderID))
{
outerDictionary[senderID] = new Dictionary<int, string>();
}
outerDictionary[senderID][numMessages] = txtSendMessage.Text;
#1
Try doing it this way:
尝试这样做:
if (!outerDictionary.ContainsKey(senderID))
{
outerDictionary[senderID] = new Dictionary<int, string>();
}
outerDictionary[senderID][numMessages] = txtSendMessage.Text;