2017-07-27 43 views
0

我想弄清楚如何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}; 
} 
+0

显示项目(来自'temp'变量)的代码似乎没问题(它应显示保存为关键字的整个字符串)。它表明字典的键可能只是单个字符。请验证将项目添加到字典的代码。 –

+0

你能告诉我们为字典添加值的代码吗? – FCin

+0

添加方法和方法调用。 –

回答

0

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

根据意见的对话中,如果要删除从购物者收集选定Customer,您可以更改该行:

temp.RemoveAt (index-1);

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

该解决方案但是,仅需要在Dictionary中进行额外的搜索以查找要删除的项目的关键字。考虑保持项目索引和项目本身之间的映射,或者将字典更改为List<Customer>

相关问题