在C#中动态添加项目列表

时间:2015-01-22 09:54:06

标签: c# list

所以我想在列表中输入输入项目,但它只添加一个项目。

我做错了什么

public void AddItems(List<Things> thing)
 {
    Console.Write("\nEnter Product ID : ");
    int choice = Convert.ToInt32(Console.ReadLine());
    Console.Write("\nEnter Quantity : ");
    int quantity = Convert.ToInt32(Console.ReadLine());
    var item = thing.FirstOrDefault(i => i.ID == choice);

   if (item.ID == choice)
     {
       List<SelectedThing> selectedthing = new List<SelectedThing>();
       {
          var total = item.Price * quantity;
          selectedthing.Add(new SelectedProduct(this.ID = item.ID, this.Price = item.Price, this.Quantity = quantity, this.Name = item.Name));
          foreach (var items in selectedthing)
           {
             Console.WriteLine("\nYou Selected {0} and {1} quantity.Total Is {2:C}\n", items.Name, quantity, total);
            }
        }
   }
Console.WriteLine("\nWant To Add More Item..?? Press Y for Yes or E to End \n");
Console.Write("\nYour Option  : ");
string repeat = Console.ReadLine().ToLower();
 if (repeat == "y")
 {
   AddItems(thing);
  }
}

现在,当按y 后重复过程时,它不会再添加列表 List<SelectedThing> 中的一个项目,它只显示一个项目。

3 个答案:

答案 0 :(得分:2)

每次调用方法时,您当前都在创建一个新列表:

List<SelectedThing> selectedthing = new List<SelectedThing>();

如果要将新项目添加到同一列表中,那么您也必须将该列表传递给该方法。类似的东西:

public void AddItems(List<Things> thing, List<Things> basket)
{
    ....
    ....
    if (repeat == "y")
    {
        AddItems(thing, basket);
    }
}

答案 1 :(得分:0)

因为你每次都在创建一个列表实例,

List<SelectedThing> selectedthing = new List<SelectedThing>();

使其成为会员变量。

List<SelectedThing> selectedthing = new List<SelectedThing>();
public void AddItems(List<Things> thing)
{
    Console.Write("\nEnter Product ID : ");
    int choice = Convert.ToInt32(Console.ReadLine());
    Console.Write("\nEnter Quantity : ");
    int quantity = Convert.ToInt32(Console.ReadLine());
    var item = thing.FirstOrDefault(i => i.ID == choice);

    if (item.ID == choice)
    {

        {
            var total = item.Price * quantity;
            selectedthing.Add(new SelectedProduct(this.ID = item.ID, this.Price = item.Price, this.Quantity = quantity, this.Name = item.Name));
            foreach (var items in selectedthing)
            {
                Console.WriteLine("\nYou Selected {0} and {1} quantity.Total Is {2:C}\n", items.Name, quantity, total);
            }
        }
    }
    Console.WriteLine("\nWant To Add More Item..?? Press Y for Yes or E to End \n");
    Console.Write("\nYour Option  : ");
    string repeat = Console.ReadLine().ToLower();
    if (repeat == "y")
    {
        AddItems(thing);
    }
}

答案 2 :(得分:0)

@kjbartel更好的方法是在函数中使用两个列表作为ref类型,即

public void AddItems(ref List<Things> thing, ref List<Things> basket)
{
    ....
    ....
    if (repeat == "y")
    {
        AddItems(ref thing, ref basket);
    }
}

现在解决了创建新实例的问题。所有更改都是针对同一个实例完成的。 希望你能尝试一下。