c# - Dictionary<string, int> 增加值

标签 c# dictionary

我有一个 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/

相关文章:

c# - 使用自定义 JsonConverter 时无限转换循环

android - 想要与谷歌地图应用程序相同的卫星 View

python - 我的函数的性能从字典中删除作为其他键的子字符串的键

c# - 将 C# 类映射到 Objective-C 类中?

c# - 在 ASP.NET Core Web Api 中使用 JWT 授权检查 IP

Python - 根据相同的键对字典列表中的值求和

java - 在Java中访问2D map ( map 的 map )最有效的方法?

python为scipy中的约束动态创建字典

c# - 如何使用现有实例选择要在 IoC 容器中创建的类型

c# - 我正在尝试从 c# 中的 xml 文件读取目录并遇到问题