【问题标题】:Changing the value of a key in a Dictionary of key type string and value List of int更改键类型字符串字典和 int 值列表中键的值
【发布时间】:2020-08-07 14:06:37
【问题描述】:

我有一个 Dictionary 的键类型 stringList<int> 的值,我需要在保持 List<int> 值的同时更改键 string 值。

static void ChangeName(Dictionary<string, List<int>> studentGrades)
{
    Console.WriteLine("Please enter the student whose name you wish to change.");
    string input = Console.ReadLine();
    if (studentGrades.ContainsKey(input))
    {
        Console.WriteLine("What would you like to change " + input + " to?");
        string newname = Console.ReadLine();
        studentGrades[input] = newname;
    }
}

我知道执行studentGrades[input] = newname; 不起作用,因为它试图更改List&lt;int&gt; 的值。我也不确定是否可以更改键的值,有哪些可能的解决方法?我在Visual Studio 中收到错误CS0029

【问题讨论】:

    标签: c# list dictionary key


    【解决方案1】:

    无法修改字典键

    但你可以通过另一种方式解决这个问题。

    • 您正在检查字典是否有您的输入,如果它有键,您将给它一个新名称,但值保持不变。所以先借助TryGetValue方法获取实际值。

    • 然后,您必须删除旧密钥并添加一个带有newName 的密钥,您将提供该密钥作为输入。

    只需在您的 ContainsKey 块中添加以下部分

        studentGrades.TryGetValue(input, out var valToUpdate);
        studentGrades.Remove(input);
        studentGrades.Add(newName,valToUpdate);
    

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    您可以删除带有旧密钥 (input) 的条目,然后添加带有新密钥 (newname) 的条目:

    string input = Console.ReadLine();
    
    if (studentGrades.ContainsKey(input))
    {
        string newname = Console.ReadLine();
    
        List<int> grades = studentGrades[input];
        studentGrades.Remove(input);        // Remove an entry with old key.
        studentGrades.Add(newname, grades); // Add an entry with new key.
    }
    

    【讨论】:

    • 非常感谢,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多