我很新,你可以在我的编程中看到,我正在制作一个简单的程序练习。我想举例说明Item.price& Item.Name到Listbox2。
是否可以将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。
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 :(得分:0)
我不确定你到底在寻找什么,但也许你可以在产品结构中加入产品类型(饮料或面包)?
public struct Products
{
public string type;
public string name;
public double price;
}
然后您可以创建列表
List<Products>
并像在示例中那样在foreach循环中使用它
答案 1 :(得分: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);
}
}