c# - 在 C# 中的字典内的列表中添加数据
问题描述
- 在第 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);
}
}
}
}
解决方案
我们不需要将修改后的列表重新分配给字典值。步骤#2 是多余的。当您从步骤 #1 中检索列表时。它返回一个指向字典中列表的指针(引用)。这意味着,当您将项目插入列表变量时,字典中的列表会更新(添加新项目)。
此外,在第 3 步中,您得到了r
但未使用的。
推荐阅读
- docker - 组合后在docker容器中执行命令
- vscode-settings - Prettier 禁用某些语言不起作用
- c# - .net 核心解码的 JWT 声明类型与生成时使用的声明类型不匹配
- angular5 - ngxDaterangepickerMd in trigger event on selection of start/end date
- angular - 角度信号器问题
- android - 如何用Android RecyclerView表示列表里面的列表
- google-apps-script - 创建 Google 脚本以将表格中的值复制到表格的单独选项卡上的不同表格中
- kubernetes - kubernetes 部署一个带有版本化密钥的 pod
- r - 计算复杂 table_1 中的持续时间
- html - 简单标签图像库(CSS + jQuery)的不透明度问题