【发布时间】:2021-10-22 21:33:33
【问题描述】:
- 在第 1 步中,我编写了这段代码来访问预先存在的列表并在其中添加价值。
- 在第 2 步中,我使用新列表更新了字典。
- 再次在第 3 步中,我必须访问字典中的列表才能打印结果。
是否有任何过程或快捷方式可以直接在字典中向这个预先存在的列表添加新值而不更新它?
只需要在 Main 中编写代码。 Rest 在编译器中是硬编码的,无法更改。 您的帮助将不胜感激。欢迎提出建议:)
using System;
using System.Collections.Generic;
namespace AddNewMember
{
public class Club
{
static Dictionary<int, string> groupInfo = new Dictionary<int, string>() { { 1, "Gold" }, { 2, "Silver" }, { 3, "Platinum" } };
static Dictionary<int, List<String>> memberInfo = new Dictionary<int, List<String>>() {
{ 1, new List<string>(){ "Tom","Harry"} },
{ 2,new List<string>(){ "Sam","Peter"} },
{ 3,new List<string>(){ "Kim","Robert"} } };
public static void Main(string[] args)
{
//Write your code here. Above part is hardcoded can't be changed
Console.WriteLine("Group Name :");
string gName = Console.ReadLine();
int num = 0;
foreach (KeyValuePair<int, string> VARIABLE in groupInfo)
{
if (VARIABLE.Value == gName)
{
num = VARIABLE.Key;
}
}
Console.WriteLine("Member Name:");
string name = Console.ReadLine();
//Step 1
List<string> l = memberInfo[num];
l.Add(name);
//Step 2
memberInfo[num] = l;
//Step 3
List<string> r = memberInfo[num];
foreach (var VARIABLE in r)
{
Console.WriteLine(VARIABLE);
}
}
}
}
【问题讨论】:
标签: c# list dictionary collections generic-collections