我有一个Dictionary<string, int>
,我正在阅读列表中的一些字符串...我想将它们添加到字典中,但是如果字符串已经在字典中,我希望它的值增加1字典<string, int>增加值
我试过的代码如下,但是有一些字符串会随着每个输入而增加..是不是有问题?
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach (String recordline in tags)
{
String recordstag = recordline.Split('\t')[1];
String tagToDic = recordstag.Substring(0, (recordstag.Length-1));
if (dictionary.ContainsKey(tagToDic) == false)
{
dictionary.Add(tagToDic, 1);
}
else
{
try
{
dictionary[tagToDic] = dictionary[tagToDic] + 1;
}
catch (KeyNotFoundException ex)
{
System.Console.WriteLine("X" + tagToDic + "X");
dictionary.Add(tagToDic, 1);
}
}
}
编辑:要回答你的意见......我删除字符串的最后一个字符,因为它始终是一个空白...... 我的输入是这样的:
10000301 business 0 0,000
10000301 management & auxiliary services 0 0,000
10000316 demographie 0 0,000
10000316 histoire de france 0 0,000
10000347 economics 0 0,000
10000347 philosophy 1 0,500
和我只需要像“业务”或“管理&辅助服务”等字符串。
对于它的价值,你可以清理你的代码*很多*:http://codepad.org/3DD4H1zl – Ryan
样品输入显示你所看到的行为的字符串? –
请给出你想要操纵的字符串的例子,以澄清你的问题 – lafama