首页 > 解决方案 > 在 C# 中的字典内的列表中添加数据

问题描述

是否有任何过程或快捷方式可以直接在字典中向这个预先存在的列表中添加新值而不更新它?

只需要在 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#listdictionarycollectionsgeneric-collections

解决方案


我们不需要将修改后的列表重新分配给字典值。步骤#2 是多余的。当您从步骤 #1 中检索列表时。它返回一个指向字典中列表的指针(引用)。这意味着,当您将项目插入列表变量时,字典中的列表会更新(添加新项目)。

此外,在第 3 步中,您得到了r但未使用的。


推荐阅读