我有一个 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);
}
}
}
编辑:为了回答您的意见...我正在删除字符串的最后一个字符,因为它始终是一个空格... 我的输入是这样的:
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
我只想要“业务”或“管理和辅助服务”等字符串。
最佳答案
您正在拆分输入字符串数组中的每个字符串并选择字符串数组中的第二个字符串。 然后您将使用 SubString 删除第二个字符串的最后一个字符。因此,所有仅在最后一个字符不同的字符串都将被视为相同并递增。这就是为什么您可能会看到“一些字符串随着每次输入而增加”。
编辑:如果删除最后一个字符的目的是删除空格,请改用 String.Trim。 另一个编辑是使用 TryGetValue 而不是 ContainsKey,它可以更好地增加您的值(value)。代码已在下方编辑。
试试这个:
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;
}
关于c# - Dictionary<string, int> 增加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8406165/