字典外的编号菜单<>



我正在尝试弄清楚如何Console.WriteLine编号的字典。

CollectionManager shoppers =
new CollectionManager
{
Carts = new List<Inventory>(),
Dictionary = new Dictionary<string, List<Inventory>>()
};

我尝试过的方法:

public static void DisplayShoppers(CollectionManager shoppers)
{          
List<string> temp =new List<string>();
temp = shoppers.Dictionary.Keys.ToList();
for (int i = 0; i < temp.Count; i++)
{
Console.WriteLine((i + 1) + ". Name: " + temp[i]);
}
Console.WriteLine("Pick a card to Shopper: ");
int index = int.Parse(Console.ReadLine());
if (index > temp.Count || index < 1)
{
return ;
}
temp.RemoveAt(index - 1);
}

它有点工作?但它只是打印字典中每个条目的第一个字母。

switch (choice)
{
case 1:
Customers temp = CreateCustomers();
shoppers.Dictionary.Add(temp.ToString(), new List<Inventory>());
break;
case 2:
DisplayShoppers(shoppers);
break;
}
//method for creating customer 
static Customers CreateCustomers()
{
Console.WriteLine("Create a Customer.");
string name = Console.ReadLine();
return new Customers {Name = name};
}

在控制台中显示完整的客户名称方面,该代码似乎是正确的。

根据评论中的对话,如果要从购物者集合中删除选定的Customer,可以更改以下行:

temp.RemoveAt (index-1);

shoppers.Dictionary.Remove(shoppers.Dictionary.ElementAt (index-1).Key);

但是,此解决方案需要在Dictionary中进行其他搜索,才能找到要删除的项目的键。考虑保留项目索引和项目本身之间的映射,或者只是将字典更改为List<Customer>

最新更新