问题描述
这是我第一次需要用字典做一些事情。我无法覆盖 item.Value,我不知道该怎么做。
编写一个程序,从标准输入行到文件末尾 (EOF) 每行读取一只猴子的名字,并按以下格式读取它收集的香蕉数量:
monkey_name;香蕉数量
程序将猴子的名字和它们收集的香蕉数量以示例输出中给出的格式写入标准输出,根据猴子的名字按字典序升序!
输入:
Jambo;10
Kongo;5
Charlie;12
Jambo;10
Koko;14
Kongo;10
Jambo;5
Charlie;8
输出:
Charlie: 20
Jambo: 25
Koko: 14
Kongo: 15
这是我的代码:
string input;
string[] row = null;
IDictionary<string,int> majom = new SortedDictionary<string,int>();
int i;
bool duplicate = false;
while ((input = Console.ReadLine()) != null && input != "")
{
duplicate = false;
row = input.Split(';');
foreach(var item in majom)
{
if(item.Key == row[0])
{
duplicate = true;
i = int.Parse(row[1]);
item.Value += i; //I'm stuck at here. I dont kNow how am i able to modify the Value
}
}
if(!duplicate)
{
i = int.Parse(row[1]);
majom.Add(row[0],i);
}
}
foreach(var item in majom)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
抱歉我的英语不好,我已经尽力了。
解决方法
class Program
{
static void Main()
{
string input;
string[] row;
IDictionary<string,int> majom = new SortedDictionary<string,int>();
//int i;
//bool duplicate = false;
while ((input = Console.ReadLine()) != null && input != "")
{
//duplicate = false;
row = input.Split(';');
// Usually dictionaries have key and value
// hier are they extracted from the input
string key = row[0];
int value = int.Parse(row[1]);
// if the key dose not exists as next will be created/addded
if (!majom.ContainsKey(key))
{
majom[key] = 0;
}
// the value coresponding to the already existing key will be increased
majom[key] += value;
//foreach (var item in majom)
//{
// if (item.Key == row[0])
// {
// duplicate = true;
// i = int.Parse(row[1]);
// item.Value += i; I'm stuck at here. I dont know how am i able to modify the Value
// }
//}
//if (!duplicate)
//{
// i = int.Parse(row[1]);
// majom.Add(row[0],i);
//}
}
foreach (var item in majom)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
}
}