Menu
CoddyTech

回顾:HashMap

本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 51 课,共 66 课。

challenge icon

挑战

简单

创建一个名为 ProcessDictionary 的方法,它接受一个 Dictionary<string, int> 和一个操作数组作为参数。该方法应执行以下操作:

  1. 如果操作是 "GET key",则打印该键对应的值;如果键不存在,则打印 "Not found"
  2. 如果操作是 "CHECK key",则键存在时打印 "Exists",否则打印 "Not found"
  3. 如果操作是 "MODIFY key value",则执行以下操作:
    • 如果键存在且其值与提供的值相同,则将其值加 1
    • 如果键存在但值不同,则移除该键
    • 如果键不存在,则使用提供的值添加该键

处理完所有操作后,返回更新后的 Dictionary。

亲手试试

using System;
using System.Collections.Generic;

class Program
{
    public static Dictionary<string, int> ProcessDictionary(Dictionary<string, int> data, string[] operations)
    {
        // 在这里编写你的代码
    }

    static void Main(string[] args)
    {
        // 用一些数据初始化字典
        Dictionary<string, int> data = new Dictionary<string, int>
        {
            { "Apple", 10 },
            { "Banana", 5 },
            { "Orange", 7 }
        };

        // 操作示例
        string[] operations = new string[] 
        {
            "GET Apple",
            "CHECK Mango", 
            "MODIFY Banana 5",
            "MODIFY Orange 8",
            "MODIFY Mango 3"
        };

        Dictionary<string, int> result = ProcessDictionary(data, operations);
        
        // 显示结果
        Console.WriteLine("Updated Dictionary:");
        foreach (var item in result)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

逻辑与流程中的所有课

自己练习: C# 在线编译器