我有一个Dictionary<string, int>,我正在从列表中读取一些字符串...我想在字典中添加它们,但如果字符串已经在字典中,我希望它的值增加1.
我尝试的代码如下所示,但是有一些字符串随着每个输入而增加..是不是有问题?
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:回答你的评论...我删除字符串的最后一个字符,因为它总是一个空格...我的输入如下:
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
Run Code Online (Sandbox Code Playgroud)
我只想要像"业务"或"管理和辅助服务"等字符串.
您正在拆分输入字符串数组中的每个字符串并选择字符串数组中的第二个字符串.然后,您将使用SubString删除此第二个字符串的最后一个字符.因此,仅在最后一个字符中不同的所有字符串将被视为相同且递增.这就是为什么你可能会看到"随着每次输入而增加的一些字符串".
编辑:如果删除最后一个字符的目的是删除空格,请改用Use.Trim.另一个编辑是使用TryGetValue而不是ContainsKey,它可以更好地增加您的值.代码编辑如下.
试试这个:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach(string recordline in tags)
{
string recordstag = recordline.Split('\t')[1].Trim();
int value;
if (!dictionary.TryGetValue(recordstag, out value))
dictionary.Add(recordstag, 1);
else
dictionary[recordstag] = value + 1;
}
Run Code Online (Sandbox Code Playgroud)