Search code examples
c#listdictionarycollectionsgeneric-collections

Adding Data in List inside a Dictionary in C#


  • In Step 1 I wrote this code to access pre-existing list & add value in it .
  • In Step 2 I updated the dictionary with new list.
  • In Step 3 again I have to access the list inside dictionary to print the result.

Is there any process or shortcut to add new values to this pre-existing list directly inside dictionary without updating it?

Only have to write the code inside Main. Rest was hardcoded in the compiler & can't be changed. Your Help will be appreciated. Suggestions are welcome :)

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);
            }

        }
    }
}

Solution

  • We don't need to re-assign modified list into dictionary value. Step #2 is redundant. When you retrieve the list from step #1. It return a pointer (reference) to the list in the dictionary. It means, when you perform insert an item into the list variable, the list in dictionary is updated (new item added).

    Also, In step #3, you get the r but not used.