c# - 无法使用带有嵌入列表(例如字典)的字典来解决我的问题>
问题描述
但是,尝试将列表对象添加到字典中,我无法理解您拥有它们的键的概念,因此如果没有键违规,您将无法执行 .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;
}
这仅使用一个列表,但是我需要能够将其转换为嵌入此列表的字典
解决方案
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);
推荐阅读
- r - 在不平衡设计中基于多个变量计算数据的均值和 se
- vue.js - Nuxt URL.createObjectURL 不是函数
- twitter-bootstrap - 引导行 - 2 列(文本右,图像左) - 需要图像正确填充左列并做出响应?
- google-cloud-platform - 我可以在部署 Cloud Functions 时更改用于存储工件的默认 Cloud Storage 存储分区区域吗?
- r - 检查对象是否为 Null 或未定义
- r - 如何检查文件是否为栅格?
- python - 使用滑动步骤重塑矩阵
- mysql - SQL 到 Django 的翻译
- bash - 命令返回一个字符串列表,但想把它变成一个数组,这样我就可以遍历它们
- acumatica - 自定义视图 GI 导航