c# - 增加字典中存在的键的值

标签 c# dictionary

我正在尝试创建一致性。 我有字典,其中键 - 是单词和值 - 是这个词的频率 如果字典中存在单词,我需要增加该单词的值。 我正在使用 ContainsKey 检查单词是否存在,机器人不明白如何增加值(value)

    string[] words = SplitWords(lines);

    foreach (var  word in words)
    {
            int i = 0;
            if (!concordanceDictionary.ContainsKey(word))
            {
                concordanceDictionary.Add(word, i);
            }
            else
            {

            }
            foreach (KeyValuePair<string, int> pair in concordanceDictionary)
            {
                Console.WriteLine("{0}:{1}",pair.Key, pair.Value);
           }
        }

最佳答案

您需要使用 indexer属性:

if (!concordanceDictionary.ContainsKey(word))
{
    concordanceDictionary.Add(word, 1);
}
else
{
    concordanceDictionary[word]++;
}

关于c# - 增加字典中存在的键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26578693/

相关文章:

c# - 等待事件从任务列表中触发

c# - 如何检测屏幕亮度或系统音量何时发生变化?

python - 通过从 json 创建新对象来消除嵌套

linux - 预设字典是否仅对前 32 K 字节的数据有用?

c# - 如何正确地将数值注入(inject) JavaScript?

c# - int.TryParse 语法糖

c# - LINQ - 在 IEnumerable 中选择第二个项目

python - 从字典中绘制每月天气数据

python递归字典转换为字符串

java - 如何从服务器接收到的 xmlrpc 处理/读取 java 对象