簡體   English   中英

更改鍵類型字符串字典和 int 值列表中的鍵值

[英]Changing the value of a key in a Dictionary of key type string and value List of int

我有一個鍵類型stringList<int>值的Dictionary ,我需要在保持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<int>的值。 我也不確定是否可以更改鍵的值,有哪些可能的解決方法? 我在Visual Studio中收到錯誤CS0029

無法修改字典鍵

但你可以通過另一種方式解決這個問題。

  • 您正在檢查字典是否有您的輸入,如果它有鍵,您將給它一個新名稱,但值保持不變。 所以借助TryGetValue方法首先獲取實際值。

  • 然后,您必須刪除舊密鑰並添加一個newName您將作為輸入提供的新名稱的密鑰。

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

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

您可以使用舊鍵 ( 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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM