[英]convert List<Dictionary<string, string>> to Dictionary<string, Dictionary<string, string>>
[英]Cannot wrap my head around using a Dictionary with imbedded list such as dictionary<string, list<string>>
嘗試將列表對象添加到字典中,但是,我無法理解您擁有它們的鍵的概念,因此您無法在沒有鍵沖突的情況下執行 .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);
我不確定我是否理解你的問題,但這里有一些關於如何使用包含一般列表的字典的解釋。
你有一個由一個鍵和一個列表組成的字典。
Dictionary<string, List<int>> dictionaryWithList = new Dictionary<string, List<int>>();
如果要將某些內容保存到此列表中,則必須先創建一個鍵值對。 這意味着向包含鍵和列表的字典添加一個元素。 如果您想在添加鍵值對時填充列表,您可以執行以下操作:
List<int> myList = new List<int>();
myList.Add(5);
myList.Add(6);
myList.Add(7);
dictionaryWithList.Add("test", myList);
現在您有一個包含 5、6 和 7 的列表,您可以使用字典中的“test”鍵訪問它們。
如果您想訪問您只需使用的列表:
dictionaryWithList["test"]
因此,如果您想將一個新號碼添加到具有“test”鍵的列表中,那么您可以使用:
dictionaryWithList["test"].Add(42)
如果您想避免遇到因鍵不存在而導致的異常,請先測試鍵是否存在:
if(dictionaryWithList.ContainsKey("test"))
如果這沒有幫助您了解有關您的問題的更多信息,請通知我:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.