2013-08-20 94 views
1

我很新,因为你可以在我的编程中看到,我正在做一个简单的程序练习。我想举例子Item.price & Item.Name到Listbox2中。列表名称到变量c#

是否可以将arrayName放入一个变量并放入foreach循环中? 只是为了防止一个非常长的IF循环或开关,或一个while循环。

For example : 
    Array variable = Drinks; 
    foreach(Product item in VARIABLE) 
         { 
          listBox2.Items.Add(item.ProductName + item.Price); 
         } 

PS:我已经与你放置drinkList到临时列表,然后把它叫做product.Name和/或Product.price的临时列表tryed。

public partial class Form1 : Form 
{ 
    List<Product> Drinks = new List<Product>() {new Product("Coca Cola", 1.2F), new Product("Fanta", 2.0F), new Product("Sprite", 1.5F) }; 
    List<Product> Bread = new List<Product>() { new Product("Brown Bread", 1.2F), new Product("White Bread", 2.0F), new Product("Some otherBread", 1.5F) }; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     listBox1.Items.Clear(); 

     if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0) 
     { 
      foreach (Product item in Drinks) 
      { 
       listBox1.Items.Add(item.ProductName); 
      } 
     } 
     else 
     { 
      foreach (Product item in Bread) 
      { 
       listBox1.Items.Add(item.ProductName); 
      } 
     } 
    } 

    private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) 
    { 
     // do something here 
    } 
} 

public class Product 
{ 
    private string productName; 
    private float price; 

    public Product(string productName, float price) 
    { 
     this.ProductName = productName; 
     this.Price = price; 
    } 

    public string ProductName 
    { 
     get { return productName; } 
     set { productName = value; } 
    } 

    public float Price 
    { 
     get { return price; } 
     set { price = value; } 
    } 
} 
+0

你得到了什么错误? – SolarBear

+0

无,我只是试图找到一种新的方法来使我的代码语法更小,更高效。 – mrName

+5

既然你不想解决一个特定的问题,你可以在http://codereview.stackexchange.com上发布更好的答案。 –

回答

0

我不知道你在找什么,但也许你可以把产品类型(饮料或面包)放在结构中?

public struct Products 
{ 
    public string type; 
    public string name; 
    public double price; 
} 

然后,您可以创建列表

List<Products> 

,当你在你的例子一样使用它在你的foreach循环

0

这听起来像你要找的是什么:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    listBox1.Items.Clear(); 

    // start with Bread and change if necessary. 
    List<Product> products = Bread; 

    if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0) 
    { 
     //change the value of "products" 
     products = Drinks; 
    } 

    foreach (Product item in products) 
    { 
     listBox1.Items.Add(item.ProductName + item.Price); 
    } 

}