>,c#,list,dictionary"/>

首页 > 解决方案 > 无法使用带有嵌入列表(例如字典)的字典来解决我的问题>

问题描述

但是,尝试将列表对象添加到字典中,我无法理解您拥有它们的键的概念,因此如果没有键违规,您将无法执行 .add

在处理购物清单程序时,我需要将库存添加到客户的购物车中,将其从库存中删除,然后将其添加到字典中。

    public static Inventory AddToCart(List<Inventory> Inventory)
    {
        // this method moves a dvd from inventory to the shopping cart.
        int i = 0;
        int iInput = 0;
        Inventory newCart = null;
        if (Inventory.Count > 0)
        {

            foreach (Inventory obj in Inventory)
            {
                ++i;
                Console.WriteLine("[" + i + "] " + obj.ToString());
            }
            iInput = Validation.GetInt("Please Choose an item to add to cart: ");
            Console.Write($"Move item at record: #{iInput - 1} to shopping cart: (y or n)");
            string sInput = Console.ReadLine();
            if (string.IsNullOrEmpty(sInput))
            {
                Console.WriteLine("\r\nNo Valid number was chosen: ");
            }
            else
                switch (sInput.ToLower())
                {
                    case "y":
                        {
                            newCart = Inventory[iInput - 1];
                            Inventory.RemoveAt(iInput - 1);
                        }
                        break;
                    case "n":
                    case null:
                    case "":
                        {
                            Console.WriteLine("\r\nNo Valid number was chosen: ");
                        }
                        break;
                    default:
                        {
                            Console.WriteLine("Keeping item in Inventory");
                        }
                        break;
                }
        }
        else
        {
            Console.WriteLine("\nNo records were found in the Shopping Cart");
        }
        return newCart;
    }

这仅使用一个列表,但是我需要能够将其转换为嵌入此列表的字典

标签: c#listdictionary

解决方案


    string newKey = "NEW KEY";
    string firstListElement = "FIRST";
    Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
    if (dict.ContainsKey(newKey)) { 
        // you need to throw an exception or return some signal to exit function
    }
    dict.Add(newKey, new List<string>());
    dict[newKey].Add(firstListElement);

推荐阅读